加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.net – 如何创建只读依赖属性?

发布时间:2020-12-14 01:09:15 所属栏目:百科 来源:网络整理
导读:如何创建只读依赖属性?这样做的最佳做法是什么? 具体来说,最糟糕的是,没有实现的事实 DependencyObject.GetValue() 它将System.Windows.DependencyPropertyKey作为参数。 System.Windows.DependencyProperty.RegisterReadOnly返回一个DependencyProperty
如何创建只读依赖属性?这样做的最佳做法是什么?

具体来说,最糟糕的是,没有实现的事实

DependencyObject.GetValue()

它将System.Windows.DependencyPropertyKey作为参数。

System.Windows.DependencyProperty.RegisterReadOnly返回一个DependencyPropertyKey对象,而不是DependencyProperty。所以如果你不能调用GetValue,你应该如何访问你的只读依赖属性?或者你应该以某种方式将DependencyPropertyKey转换为一个普通的旧的DependencyProperty对象?

建议和/或代码将是非常感谢!

这很容易,实际上(通过 RegisterReadOnly):
public class OwnerClass : DependencyObject // or DependencyObject inheritor
{
    private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey
        = DependencyProperty.RegisterReadOnly("ReadOnlyProp",typeof(int),typeof(OwnerClass),new FrameworkPropertyMetadata((int)0,FrameworkPropertyMetadataOptions.None));

    public static readonly DependencyProperty ReadOnlyPropProperty
        = ReadOnlyPropPropertyKey.DependencyProperty;

    public int ReadOnlyProp
    {
        get { return (int)GetValue(ReadOnlyPropProperty); }
        protected set { SetValue(ReadOnlyPropPropertyKey,value); }
    }

    //your other code here ...
}

仅当在private / protected / internal代码中设置值时,才使用该键。由于受保护的ReadOnlyProp设置器,这对您是透明的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读