你如何创建一个只读依赖属性? [英] How do You Create a Read-Only Dependency Property?

查看:174
本文介绍了你如何创建一个只读依赖属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个只读扶养的财产?什么是最好的做法,这样做?

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()  

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

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

System.Windows.DependencyProperty.RegisterReadOnly 返回A D ependencyPropertyKey 对象,而不是一个的DependencyProperty 。因此,如何是你应该访问您的只读依赖属性,如果你不能做任何调用的GetValue?或者,您应该以某种方式转换由其DependencyPropertyKey 成一个普通的老式的DependencyProperty 对象?

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?

咨询和/或code将大大AP preciated!

Advice and/or code would be GREATLY appreciated!

推荐答案

这很容易,实际上是:

public class OwnerClass : DependencyObject // or DependencyObject inheritor
{
    private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey
        = DependencyProperty.RegisterReadOnly("ReadOnlyProp", typeof(int), typeof(OwnerClass),
            new FrameworkPropertyMetadata((int)0,
                FrameworkPropertyMetadataOptions.None,
                new PropertyChangedCallback(OnReadOnlyPropChanged)));

    public static readonly DependencyProperty ReadOnlyPropProperty
        = ReadOnlyPropPropertyKey.DependencyProperty;

    public int ReadOnlyProp
    {
        get { return (int)GetValue(ReadOnlyPropProperty); }
        protected set { SetValue(ReadOnlyPropPropertyKey, value); }
    }

    private static void OnReadOnlyPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((OwnerClass)d).OnReadOnlyPropChanged(e);
    }

    //your other code here ...
}

您使用的关键,只有当你设置私人/保护/内部code的值。由于保护 ReadOnlyProp 二传,这是透明的你。

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.

这篇关于你如何创建一个只读依赖属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆