I’ve seen this question a number of times in the Silverlight Forums, so instead of just answering it one more time I decided to answer it here so I can refer back to this. The question generally looks like this:
I have create a dependency property and the setter isn’t getting called during data binding. My dependency property is declared as follows:
public class MyClass : Control
{
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set
{
SetValue(MyPropertyProperty, value);
// some custom code here
}
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new PropertyMetadata(0));
}
The reason why the setter isn’t called here (at least the way I understand this), is that when data binding sets this value it isn’t calling the public property. Instead it is using the SetValue on the dependency object instead. So the custom code is never called. What you need to do is add a PropertyChangedCallback to the DependencyProperty registration as follows:
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set
{
SetValue(MyPropertyProperty, value);
}
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new PropertyMetadata(0, MyPropertyChanged));
private static void MyPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((MyClass)o).OnMyPropertyChanged((int)e.NewValue);
}
private void OnMyPropertyChanged(int newValue)
{
// custom code goes here instead
}
Now whenever the property changes the OnMyPropertyChanged method will get called. Notice that this is where you put your custom code to handle the property changing. This code will get called when the public property setter is called or when the property is changed using the SetValue method.
More information on Dependency Properties can be found here.