如何创建只读依赖项属性?

时间:2022-09-11 18:06:13

How do you create a read-only dependancy property? What are the best-practices for doing so?

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

Specifically, what's stumping me the most is the fact that there's no implementation of

具体地说,最让我为难的是没有实现的事实

DependencyObject.GetValue()  

that takes a System.Windows.DependencyPropertyKey as a parameter.

这需要一个System.Windows。DependencyPropertyKey作为参数。

System.Windows.DependencyProperty.RegisterReadOnly returns a DependencyPropertyKey object rather than a DependencyProperty. So how are you supposed to access your read-only dependency property if you can't make any calls to GetValue? Or are you supposed to somehow convert the DependencyPropertyKey into a plain old DependencyProperty object?

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

Advice and/or code would be GREATLY appreciated!

非常感谢您的建议和/或代码!

1 个解决方案

#1


120  

It's easy, actually (via RegisterReadOnly):

实际上很简单(通过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 ...
}

You use the key only when you set the value in private/protected/internal code. Due to the protected ReadOnlyProp setter, this is transparent to you.

只有在私有/受保护/内部代码中设置值时才使用该键。由于受保护的ReadOnlyProp setter,这对您是透明的。

#1


120  

It's easy, actually (via RegisterReadOnly):

实际上很简单(通过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 ...
}

You use the key only when you set the value in private/protected/internal code. Due to the protected ReadOnlyProp setter, this is transparent to you.

只有在私有/受保护/内部代码中设置值时才使用该键。由于受保护的ReadOnlyProp setter,这对您是透明的。