Dependency 属性 系统如何知道特定的 dependency 属性 值属于哪个对象实例

How does the Dependency Property system know to which object instance a pirticular dependency property value belongs to

我是 WPF 新手,正在看 this 文章。我确定我问的是一个非常基本的问题,但找不到答案。至少只要在正确的方向上轻推一下,我们将不胜感激。 我创建了一个 wpf 应用程序,然后如下派生了一个 TextBox class 并在其上定义了一个依赖对象。

public class TextBoxEx : TextBox
{
    public string SecurityId
    {
        get
        {
            return (string)GetValue(SecurityIdProperty);
        }
        set
        {
            SetValue(SecurityIdProperty, value);
        }
    }

    public static readonly DependencyProperty
        SecurityIdProperty = DependencyProperty.Register("SecurityId",
        typeof(string), typeof(TextBoxEx),
        new PropertyMetadata(""));
}

在 window 构造函数中我看到了这个。

public MainWindow()
{
    InitializeComponent();

    TextBoxEx t1 = new TextBoxEx();
    t1.SecurityId = "abc";

    TextBoxEx t2 = new TextBoxEx();
    var secId = t2.SecurityId;

}   

我看到从 t2.SecurityId 分配的 secId 是“”,而我预计它是 "abc"。

那么 WPF 依赖项 属性 系统如何知道依赖项 属性 值属于哪个对象实例?我没看到 this 参数传递给 dp 属性 系统,它怎么知道的?

我认为神奇之处在于 GetValue 的实现,它有点复杂:http://www.abhisheksur.com/2011/07/internals-of-dependency-property-in-wpf.html

SecurityId 是一个实例(即非静态)属性,它调用实例方法 DependencyObject.GetValue()DependencyObject.SetValue().

如果你想在某处看到this关键字,你可以这样写属性:

public string SecurityId
{
    get { return (string)this.GetValue(SecurityIdProperty); }
    set { this.SetValue(SecurityIdProperty, value); }
}