问题 DependencyProperty默认值


我正在尝试在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,我会得到一个空引用异常。


7650
2018-05-05 08:50


起源

第二个参数是属性类型,第三个参数是控件的类型,请注意,在示例中交换它们。 - vorrtex
那是一个愚蠢的错误。谢谢。 - Echilon
@vorrtex:请将其作为答案发布...... - H.B.


答案:


发表评论作为答案。

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

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

13
2017-08-27 09:59



谢谢,这是一个容易犯的错误。 - Echilon