2011-05-05 161 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