I think I’m missing something very fundamental here.
I’ve created a UserControl with a DependencyProperty, defined as such:
public static DependencyProperty SpinnerColourProperty = DependencyProperty.Register("SpinnerColour", typeof(Color), typeof(LoadingControl), new PropertyMetadata(Colors.Black));
public Color SpinnerColour
{
get
{
return (Color)GetValue(SpinnerColourProperty);
}
set
{
SetColour(value);
SetValue(SpinnerColourProperty, value);
}
}
(Yes, I prefer British-English… so sue me :P)
The SetColour method, as expected, changes how the control looks.
If in my code I write customControl1.SpinnerColour = Colors.Red then the control will correctly change the colour both of the property and of the visual effect which is applied through the setter. (I can even observe this change if I play around with the property in Visual Studio’s designer!)
However, if I apply a data binding to that property and then change the element it’s bound to, the value of the property will change, but the setter will never be called and the actual display will never change.
So for example, if I define a button and my control:
<my:MyControl x:Name="myControl1" SpinnerColour="{Binding ElementName=button1, Path=Background.Color, Mode=TwoWay}" />
<Button Content="Button" Height="23" Name="button1" Click="button1_Click" />
And the Click event changes the colour of the buttons background as such:
private void button1_Click(object sender, RoutedEventArgs e)
{
button1.Background = new SolidColorBrush(Colors.Red);
}
Then if I check the SpinnerColour property using the debugger, it’ll be red. However, as I wrote, the setter is never called, and the actual control never changes it’s colour.
What am I doing wrong?
You’re misusing dependency properties.
The native CLR property that calls
SetValueis only used when you set the property in code.The binding infrastructure calls
SetValuedirectly (instead of using reflection), so your code never runs.You should never put any code other than
GetValueandSetValuein a DependencyProeprty wrapperInstead, you need to specify a
ValueChangedCallbackin the DependencyProperty registration, as the second parameter to thePropertyMetadataconstructor.