DependencyProperty默认值

时间:2011-05-05 08:50:49

标签: wpf binding dependency-properties default-value

我正在尝试在WPF中使用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”的类型不匹配。但是,如果我保留默认值,当窗口加载时,由于未设置DisplayModeProperty,我会得到一个空引用异常。

1 个答案:

答案 0 :(得分:13)

发表评论作为答案。

根据msdn DependencyProperty.Register Method,语法看起来如此:

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

在您的情况下,ownerType为TescoFoodSummary,propertyType为Orientation,因此参数具有以下位置:

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