75

読み取り専用の依存関係プロパティをどのように作成しますか?そうするためのベストプラクティスは何ですか?

具体的には、私を最も困惑させているのは、

DependencyObject.GetValue()  

それはパラメータとしてを取りSystem.Windows.DependencyPropertyKeyます。

System.Windows.DependencyProperty.RegisterReadOnlyependencyPropertyKeyではなくDオブジェクトを返しますDependencyProperty。では、GetValueを呼び出せない場合、読み取り専用の依存関係プロパティにどのようにアクセスする必要がありますか?それとも、どういうわけかDependencyPropertyKeyを単純な古いDependencyPropertyオブジェクトに変換することになっていますか?

アドバイスやコードをいただければ幸いです。

4

1 に答える 1

156

実際には(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セッターが保護されているため、これは透過的です。

于 2009-07-13T23:11:06.050 に答える