Reputation: 48
When I try to bind a label's foreground to a brush property (CurrentBrush) that implements INotify, the foreground doesn't get updated when the value of CurrentBrush changes. I've done other bindings in here to test and they seem to work fine, it's just the Brush property.
Initially, the foreground of the label is magenta which suggests the binding works once at least. Any ideas as to why it won't update on subsequent changes (for example, when the button is clicked)?
(I actually ran into this problem in a bigger project where I was binding the SelectedColor of a Color Picker control to the Stroke property (which is a Brush) of an element. It wouldn't work, so I tried to isolate what could be causing the issue and this is where I ended up - any help would be appreciated!)
The xaml:
<Label Content="Testing Testing 123" Name="label1" VerticalAlignment="Top" />
<Button Content="Button" Name="button1" Click="button1_Click" />
And here's the code behind:
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;
}
}
Upvotes: 1
Views: 573
Reputation: 2190
Defining binding source means that UI will listen to changes in that source,thats why when you change CurrentBrush to other color it won't affect the ui to avoid that you can set the color of the brush, in this way the source remains the same object and you just modify the properties:
setting brush - you cant use Brushes.Magenta because his properties are read only (it a frozen brush)
CurrentBrush = new SolidColorBrush(Colors.Magenta);
change color:
private void buttonBrush_Click(object sender, RoutedEventArgs e)
{
(CurrentBrush as SolidColorBrush).Color = Colors.Black;
}
Upvotes: 0