使用INotify绑定到Brush属性

时间:2013-04-21 15:42:03

标签: c# wpf xaml binding

当我尝试将标签的前景绑定到实现INotify的画笔属性(CurrentBrush)时,当CurrentBrush的值发生更改时,前景不会更新。我在这里做了其他绑定来测试它们似乎工作得很好,它只是Brush属性。

最初,标签的前景是品红色,这表明绑定至少可以工作一次。有关为什么它不会在后续更改中更新的任何想法(例如,单击按钮时)?

(我实际上在一个更大的项目中遇到了这个问题,我将一个Color Picker控件的SelectedColor绑定到一个元素的Stroke属性(这是一个Brush)。它不起作用,所以我试图隔离什么可能导致问题,这是我最终的地方 - 任何帮助将不胜感激!)

xaml:

<Label Content="Testing Testing 123" Name="label1" VerticalAlignment="Top" />
<Button Content="Button" Name="button1" Click="button1_Click" />

这是背后的代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private Brush _currentBrush;
    public Brush CurrentBrush
    {
        get { return _currentBrush; }
        set
        {
            _currentBrush = value;
            OnPropertyChanged("CurrentBrush");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

    }

    public MainWindow()
    {
        InitializeComponent();
        CurrentBrush = Brushes.Magenta;
        Binding binding = new Binding();
        binding.Source = CurrentBrush;
        label1.SetBinding(Label.ForegroundProperty, binding);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        CurrentBrush = Brushes.Black;
    }

}

1 个答案:

答案 0 :(得分:0)

定义绑定源意味着UI将侦听该源中的更改,这就是为什么当您将CurrentBrush更改为其他颜色时它不会影响ui 为了避免你可以设置画笔的颜色,这样源保持相同的对象,你只需修改属性:

设置画笔 - 你不能使用Brushes.Magenta,因为他的属性是只读的(它是一个冻结的画笔)

   CurrentBrush = new SolidColorBrush(Colors.Magenta);

改变颜色:

  private void buttonBrush_Click(object sender, RoutedEventArgs e)
   {
       (CurrentBrush as SolidColorBrush).Color = Colors.Black;
   }