支持绑定属性与私有字段或DependencyProperty的区别是什么?

时间:2017-12-12 16:27:51

标签: c# uwp dependency-properties

我有一些哲学问题:

在我的UWP应用程序中,目前我通常按如下方式定义绑定属性:

public class ExampleViewModel : BaseBind {

    // Pattern used for two-way bindings
    private object exampleObject;  // Private field for backing a binding propery
    public Object ExampleObject {
        get { return exampleObject; }
        set {
            SetProperty(ref exampleObject, value);
            OnPropertyChanged(nameof(ExampleDerivateProperty));
        }
    }

    // Simple derivate property, used in One-way bindings
    public Object ExampleDerivateProperty => (<<Boolean function about ExampleObject>>)? "Something" : "Something different";

}

就是这样......这就是我目前在MVC模式中使用的所有内容。

...但我注意到许多人更喜欢使用DependencyProperty来支持他们的绑定属性:

public string MyProperty
{

    get { return (string)GetValue(MyProperty); }
    set { SetValue(MyProperty, value); }

}

public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(MyControl), null);

如果我使用DependencyProperties而不是简单的私有字段,我可以获得哪些新的有趣功能?

我知道这个问题似乎已经在StackOverflow上得到了解答,但是这个特殊情况可能很有趣,即使有一些例子也可以深入研究。

感谢。

编辑:我知道这个主题已经有了一些答案,但它们已经过时了,因为现在我们有了UWP平台,它具有“x:Bind”编译绑定功能,还有许多其他内容已添加到C#中。 我想知道从那时起事情是否发生了变化。

1 个答案:

答案 0 :(得分:1)

  

如果我使用DependencyProperties而不是简单的私有字段,我可以获得哪些新的有趣功能?

具有依赖项属性的类必须从DependencyObject继承,这有一些缺点,这些缺点总结如下:

INotifyPropertyChanged vs. DependencyProperty in ViewModel

例如,只能从单个线程访问它们。

通常,视图模型不应包含任何依赖项属性。只有目标属性通常被定义为依赖项属性。目标属性是您在视图中绑定某些内容的属性,例如Text的{​​{1}}属性。

TextBlock与CLR和依赖源属性之间的选择无关。它是UWP中的标记扩展,由于性能原因,它在编译时将您的XAML绑定转换为代码。