WPF 中的依赖属性之间的区别

Difference between dependency properties in WPF

我在 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 片段:

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));
}

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

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

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

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

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

via

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