2011-05-05 143 views
11

我想要在WPF中使用DependencyProperty。我正在使用:DependencyProperty默認值

public static readonly DependencyProperty DisplayModeProperty = DependencyProperty.Register("DisplayMode", typeof (TescoFoodSummary), typeof (Orientation), new UIPropertyMetadata(Orientation.Vertical)); 
    /// <summary> 
    /// Gets or sets the orientation. 
    /// </summary> 
    /// <value>The orientation.</value> 
    public Orientation DisplayMode { 
     get { return (Orientation)base.GetValue(DisplayModeProperty); } 
     set { base.SetValue(DisplayModeProperty, value); } 
    } 

當我初始化窗口時,出現錯誤:默認值類型與屬性'DisplayMode'的類型不匹配。 Howevere,如果我保留默認值,當由於DisplayModeProperty沒有被設置而導致窗口加載時,我得到一個空引用異常。

+1

第二個參數是屬性類型,第三個參數是控件的類型,請注意,在你的例子中交換它們。 – vorrtex 2011-05-05 14:06:39

+0

那是一個愚蠢的錯誤。謝謝。 – Echilon 2011-05-05 19:57:16

+0

@vorrtex:請將其發佈爲答案... – 2012-08-24 21:09:04

回答

13

發佈評論爲答覆。

根據MSDN DependencyProperty.Register Method語法看起來如此:

public static DependencyProperty Register(
    string name, 
    Type propertyType, 
    Type ownerType, 
    PropertyMetadata typeMetadata 
) 

在你的情況ownerType是TescoFoodSummary和屬性類型爲Orientation,所以參數有以下職位:

DependencyProperty.Register("DisplayMode", typeof (Orientation), typeof (TescoFoodSummary), new UIPropertyMetadata(Orientation.Vertical)); 
+0

謝謝,很容易犯的錯誤。 – Echilon 2012-08-28 17:39:43