微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

与私有CLR属性相比,与私有依赖项属性绑定的工作方式不同

我有一个窗口,DataContext设置为自己这个简单的XAML布局 –

<StackPanel>
   <TextBlock Text="{Binding NameCLR}"/>
   <TextBlock Text="{Binding NameDP}"/>
</StackPanel>

代码后面我有两个属性NameCLR – CLR属性和NameDP – 依赖属性.

private string NameCLR
    {
        get { return "CLRProperty"; }
    }

    private string NameDP
    {
        get { return (string)GetValue(NameDPProperty); }
        set { SetValue(NameDPProperty,value); }
    }

    private static readonly DependencyProperty NameDPProperty =
        DependencyProperty.Register("NameDP",typeof(string),typeof(MainWindow),new UIPropertyMetadata("DPProperty"));

由于代码隐藏是部分类定义,而部分是XAML.所以,我假设私有财产应该对XAML可见.但令我惊讶的是,CLR和DP表现不同.

Private Dependency property is accessible but private CLR property
isn’t.

我把输出作为 –

DPProperty

代替

CLRProperty
DPProperty

有人能让我知道DP和CLR属性中的这种不同行为吗?

解决方法

绑定属性由Binding访问,而不是由声明类访问.像NameCLR这样的私有CLR属性是不可访问的,因此Binding将不起作用.

但是,在解析属性路径NameDP时,Binding显然会绕过该属性的CLR包装器并直接访问底层依赖项属性,该属性通过调用DependencyProperty.Register向依赖项属性系统注册.是否已将返回的DependencyProperty引用分配给类中的私有或公共静态字段无关紧要.依赖属性已为您的类注册,因此可以查找它.

来自链接here

Dependency properties on a given type are accessible as a storage table through the property system,the WPF implementation of its XAML processor uses this table and infers that any given property ABC can be more efficiently set by calling SetValue on the containing DependencyObject derived type,using the dependency property identifier ABCProperty.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐