【问题标题】:How does the Dependency Property system know to which object instance a pirticular dependency property value belongs to依赖属性系统如何知道特定依赖属性值属于哪个对象实例
【发布时间】:2016-08-28 04:56:25
【问题描述】:

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

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

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

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 属性系统,那么它是怎么知道的呢?

【问题讨论】:

    标签: .net wpf dependency-properties


    【解决方案1】:

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

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

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

    【讨论】:

    • 我想我现在明白你在说什么了。谢谢!!
    【解决方案2】:

    我觉得神奇的是GetValue的实现,有点复杂:http://www.abhisheksur.com/2011/07/internals-of-dependency-property-in-wpf.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多