【问题标题】:DependencyProperty Default Value依赖属性默认值
【发布时间】:2011-08-19 04:40:11
【问题描述】:

我正在尝试让 DependencyProperty 在 WPF 中工作。我正在使用:

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,在加载窗口时会出现空引用异常。

【问题讨论】:

  • 第二个参数是属性类型,第三个参数是控件的类型,注意,在你的例子中交换它们。
  • 这是一个愚蠢的错误。谢谢。
  • @vorrtex:请将其发布为答案...

标签: wpf binding dependency-properties default-value


【解决方案1】:

发表评论作为答案。

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

【讨论】:

  • 谢谢,很容易犯错。
猜你喜欢
  • 2011-12-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 2013-01-05
相关资源
最近更新 更多