2009-07-13 41 views
52

如何創建只讀依賴屬性?這樣做的最佳做法是什麼?如何創建只讀依賴項屬性?

具體來說,什麼是最絆倒我的事實是,有沒有

DependencyObject.GetValue() 

實現,需要一個System.Windows.DependencyPropertyKey作爲參數。

System.Windows.DependencyProperty.RegisterReadOnly返回一個D ependencyPropertyKey對象而不是DependencyProperty。那麼如果你不能對GetValue進行任何調用,你應該如何訪問你的只讀依賴項屬性?或者你應該以某種方式將DependencyPropertyKey轉換爲普通的舊DependencyProperty對象?

建議和/或代碼將非常感謝!

回答

113

這很容易,實際上是(通過RegisterReadOnly):

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

    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二傳手,這對您來說是透明的。

+0

這不是一個完整的代碼。 – Developer 2014-08-28 12:02:42