如何创建只读依赖属性?

时间:2009-07-13 23:08:13

标签: .net wpf dependency-properties

如何创建只读依赖属性?这样做的最佳做法是什么?

具体来说,最让我感到困惑的是没有实施

的事实
DependencyObject.GetValue()  

System.Windows.DependencyPropertyKey作为参数。

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

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

1 个答案:

答案 0 :(得分:134)

实际上很简单(通过RegisterReadOnly):

public class OwnerClass : DependencyObject // or DependencyObject inheritor
{
    private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey
        = DependencyProperty.RegisterReadOnly("ReadOnlyProp", typeof(int), typeof(OwnerClass),
            new FrameworkPropertyMetadata(default(int),
                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设置器,这对您来说是透明的。