Was just wondering about DependencyProperties.
Usually I’m seeing this kind of coding standard when executing some code after a DependencyProperty has changed.
public int SomeProperty
{
get { return (int)GetValue(SomePropertyProperty); }
set { SetValue(SomePropertyProperty, value); }
}
public static readonly DependencyProperty SomePropertyProperty =
DependencyProperty.Register("SomeProperty", typeof(int), typeof(MainWindow), new UIPropertyMetadata(new DependencyPropertyChangedEventHandler(OnSomePropertyChanged)));
private static void OnSomePropertyChanged(object obj, DependencyPropertyChangedEventArgs e)
{
//Some logic in here
}
But I don’t think I’ve never seen this kind of implementation –
public int SomeProperty
{
get { return (int)GetValue(SomePropertyProperty); }
set
{
SetValue(SomePropertyProperty, value);
//Execute code in here
}
}
public static readonly DependencyProperty SomePropertyProperty =
DependencyProperty.Register("SomeProperty", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0));
Is this considered a bad practice?
Thanks!
This isn’t just bad practice, this will actually result in incorrect behavior. When binding to dependency properties in XAML, the SetValue method will be called directly, not the setter. Basically, you can’t guarantee that code there will even be executed.
Source: http://www.switchonthecode.com/tutorials/wpf-tutorial-introduction-to-dependency-properties