Dro*_*ror 2 wpf dependency-properties
只是想知道DependencyProperties。
通常,在DependencyProperty更改后执行某些代码时,我会看到这种编码标准。
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
}
Run Code Online (Sandbox Code Playgroud)
但我认为我从未见过这种实现方式-
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));
Run Code Online (Sandbox Code Playgroud)
这被认为是不好的做法吗?
谢谢!
这不只是一种不好的做法,实际上会导致错误的行为。当绑定到XAML中的依赖项属性时,将直接调用SetValue方法,而不是setter方法。基本上,您不能保证在那里的代码也会被执行。
来源:http://www.switchonthecode.com/tutorials/wpf-tutorial-introduction-to-dependency-properties
这里有一点说明-不要在属性包装器中放置GetValue和SetValue调用。这是因为您永远不知道有人会通过包装器设置属性,还是直接通过SetValue调用来设置属性-因此您不想在属性包装器中放置任何多余的逻辑。例如,当您在XAML中设置依赖项属性的值时,它将不使用属性包装器-它会直接命中SetValue调用,从而绕过您碰巧放入属性包装器中的所有内容。
| 归档时间: |
|
| 查看次数: |
1294 次 |
| 最近记录: |