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

标签 .net wpf dependency-properties

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

具体来说,最让我困惑的是没有实现

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(
            nameof(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 /内部代码中设置值时才使用 key 。由于 protected ReadOnlyProp setter,这对您来说是透明的。

关于.net - 如何创建只读依赖属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1122595/

相关文章:

c# - 如何将文本框的文本双向数据绑定(bind)到依赖项属性

visual-studio-2008 - 在 XAML 中创建具有代码完成功能的属性或 DependencyProperties

.net - WPF 中的依赖属性和附加属性有什么区别?

c# - 为什么 .NET 结构应该小于 16 个字节?

.net - VB.NET to English - 这行代码应该做什么?

c# - 关于日期时间格式 "%h:%m:%s"允许小时为 "00"

c# - 系统时钟调整会影响在 C# 中运行秒表吗?

wpf - WPF中控件模板和DataTemplate的区别

c# - 用户控件数据上下文绑定(bind)

c# - MVVM Light Messenger 未按预期运行