如何创建只读依赖属性?

Gif*_*guy 63 .net wpf dependency-properties

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

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

DependencyObject.GetValue()  
Run Code Online (Sandbox Code Playgroud)

以a System.Windows.DependencyPropertyKey为参数.

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

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

Ken*_* K. 137

实际上很简单(通过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 ...
}
Run Code Online (Sandbox Code Playgroud)

只有在private/protected/internal代码中设置值时才使用密钥.由于受保护的ReadOnlyProp二传手,这对您来说是透明的.

  • 您可能想要将 `"ReadOnlyProp"` 更新为 `nameof(ReadOnlyProp)` 因为很多人可能会复制/粘贴此内容,并且他们也可能使用当前和改进的语法。 (4认同)
  • @RahulSonone 任何时候您不希望从控件类外部设置该属性。如果您不将其设置为只读,则可以在 XAML 等中设置它。 (2认同)
  • 任何控件的 ActualWidth/ActualHeight 都是一个很好的例子。 (2认同)