【问题标题】:What's the difference in backing binding properties with private fields or DependencyProperty?使用私有字段或 DependencyProperty 支持绑定属性有什么区别?
【发布时间】:2017-12-12 16:27:51
【问题描述】:

我有一些哲学问题要问你:

在我的 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# 中。 我想知道从那以后有什么变化。

【问题讨论】:

  • @WaiHaLee,是的,但那是在 2010 年,而 C# 在过去几年中已经发展:创建了 UWP 平台,它具有我通常用于 XAML 绑定的新“x:Bind”。 ..所以,我认为这个问题可能需要更新的答案...

标签: c# uwp dependency-properties


【解决方案1】:

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

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

INotifyPropertyChanged vs. DependencyProperty in ViewModel

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

一般来说,视图模型不应该包含任何依赖属性。只有 target 属性通常被定义为依赖属性。目标属性是您在视图中绑定某些内容的属性,例如TextBlockText 属性。

x:Bind 实际上与在 CLR 和依赖源属性之间进行选择无关。它是 UWP 中的一个标记扩展,出于性能原因,它可以在编译时将 XAML 绑定转换为代码。

【讨论】:

  • 好...如果您可以包含一些 DependencyProperty 的示例并使用它(VS IDE 声明它们允许动画、模板等),那就太好了。
猜你喜欢
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多