2017-03-24 104 views
-1

道歉又依賴屬性問題使用綁定的依賴項屬性XAML

以下這些問題:

XAML Binding on Dependency Property

A 'Binding' can only be set on a DependencyProperty of a DependencyObject

本教程:

http://wpftutorial.net/DependencyProperties.html

我有類似的問題。並在嘗試解決方案後沒有太多改變。

我已經做了控制庫:WpfCustomControlLibrary1

public class CustomControl1 : Control 
{ 



    static CustomControl1() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1))); 
    } 

並添加所需的回調依賴屬性:

FrameworkPropertyMetadata meta = new FrameworkPropertyMetadata(null,FrameworkPropertyMetadataOptions.Inherits, PropertyChangedCallbackMethod, OnDictionaryCoerce,false); 

    public static readonly DependencyProperty DictionaryProperty = DependencyProperty.Register("DictionaryProperty",typeof(Dictionary<string,int>), 
     typeof(CustomControl1),new FrameworkPropertyMetadata(null,FrameworkPropertyMetadataOptions.Inherits)); 

    private Dictionary<string, int> _Dictionary; 

    public static void PropertyChangedCallbackMethod(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     // I am not entirely sure what code should be implemented here, leaving it blank for now 
    } 

    private static Object OnDictionaryCoerce(DependencyObject sender,Object data) 
    { 
     return data; 
    } 

    private static bool OnValidate(object data) 
    { 
     return data is Dictionary<string, int>; 
    } 
    public Dictionary<string, int> Dictionary 
    { 
     get 
     { 
      return _Dictionary; 
     } 
     set 
     { 
      _Dictionary = value; 

     } 
    } 

} 
} 

我則嘗試將屬性設置爲一個應用程序中具有約束力,但給我一個錯誤說:

error

如何將我的依賴屬性設置爲依賴對象?或者是他們設置綁定到依賴項屬性的方法?

而不是一個依賴項屬性的基類一個依賴項對象?

+1

當您註冊一個依賴屬性你應該註冊你想要使用''Dictionary''而不是''DictionaryProperty「'的名字。如果您使用的是Visual Studio,則可能有權訪問內置代碼段。在代碼中輸入'propdp'並點擊兩次選項卡。 – Silvermind

+0

請解釋倒票 –

回答

3

註冊DP的正確名稱:

DependencyProperty.Register("Dictionary", ... 

,然後在DP包裝物業使用GetValueSetValue方法

public Dictionary<string, int> Dictionary 
{ 
    get 
    { 
     return (Dictionary<string, int>)GetValue(DictionaryProperty); 
    } 
    set 
    { 
     SetValue(DictionaryProperty, value); 
    } 
} 

private Dictionary<string, int> _Dictionary;場是沒有必要的