【问题标题】:Difference between dependency properties in WPFWPF中依赖属性之间的区别
【发布时间】:2016-03-20 20:00:39
【问题描述】:

我在 WPF 中有两个依赖属性的实现。 首先,我在网上找到的:

public class TestClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private string _test;

    public string Test
    {
       get
       {
           return _test;
       }
       set
       {
           _test = value;
           OnPropertyChanged(nameof(Test))
       }
    }
}

其次,来自 propdp sn-p:

public class TestClass
{
    public string Test
    {
         get { return (string)GetValue(TestProperty); }
         set { SetValue(TestProperty, value); }
    }
    public static readonly DependencyProperty TestProperty =     
        DependencyProperty.Register("Test", 
        typeof(string), 
        typeof(TestClass), 
        new PropertyMetadata(string.Empty));
}

它们之间有什么区别?我应该使用什么?

【问题讨论】:

  • 第一个不是依赖属性。阅读 MSDN 上的Dependency Properties Overview 文章了解所有详细信息,尤其是与普通属性的差异。

标签: c# wpf dependency-properties


【解决方案1】:

您可以绑定到DependencyProperty 一些可以实现INotifyPropertyChanged 的值。例如,如果你写:

<TextBox Content="{Binding FirstName}" />

那么 Content 是一个依赖属性,它将对绑定源的变化做出反应。

主要区别在于,普通 .NET 属性的值是 直接从您班级中的私人成员读取,而值 在调用 DependencyProperty 时动态解析 从 DependencyObject 继承的 GetValue() 方法。

当您设置依赖属性的值时,它不会存储在 对象的字段,但在提供的键和值字典中 通过基类 DependencyObject。条目的键是名称 属性和值就是你要设置的值。

via

您应该在 ViewModel 中使用简单的属性,这些属性将绑定到 WPF 对象中的依赖属性(ContentBackgroundIsChecked 和许多其他包括您将在自定义用户控件中定义的 DP) .

【讨论】:

  • 所以,在我的 ViewModels 中我应该使用简单的属性。但是我需要他们的 OnPropertyChanged 吗,就像在第一个例子中一样?我是否理解正确,仅在您的自定义控件中使用的依赖属性,如自定义文本框、图像等?
  • 如果您想使用数据绑定并在属性更改时在 UI 中做出反应,那么您需要实现 INPC 并在值更改时引发 ProprtyChanged 事件(如您的示例中所示)。是的,依赖属性允许在 XAML 语法中使用它,那么没有理由在其他场景中使用它。
猜你喜欢
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 2012-11-27
  • 2014-05-23
  • 1970-01-01
相关资源
最近更新 更多