【问题标题】:How do You Create a Read-Only Dependency Property?如何创建只读依赖属性?
【发布时间】:2010-11-10 11:47:22
【问题描述】:

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

具体来说,最让我难过的是没有实现

DependencyObject.GetValue()  

System.Windows.DependencyPropertyKey 作为参数。

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

建议和/或代码将不胜感激!

【问题讨论】:

    标签: .net wpf dependency-properties


    【解决方案1】:

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

    仅当您在私有/受保护/内部代码中设置值时才使用密钥。由于受保护的 ReadOnlyProp 设置器,这对您来说是透明的。

    【讨论】:

    • 你能否请一个我们使用的实时示例或要求,这个只读依赖属性?
    • @RahulSonone 任何时候您不希望从控件类外部设置属性。如果你不让它只读,你可以在 XAML 等中设置它。
    • ActualWidth/ActualHeight 任何控件都是一个很好的例子。
    • 您可能希望将"ReadOnlyProp" 更新为nameof(ReadOnlyProp),因为很多人可能会复制/粘贴它,他们不妨使用当前和改进的语法。
    • 没问题,谢谢你的建议。老实说,这是一个旧答案,我自己并没有“维护”答案的更新版本。此外,这些天我更多地使用 javascript 而不是 C#。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多