默认值类型与属性类型不匹配。

94

我有这个班级

public class Tooth
{
    public string Id {get;set;}
}

并且这个自定义控件

public partial class ToothUI : UserControl
{
    public ToothUI()
    {
        InitializeComponent();
    }

    public Tooth Tooth
    {
        get { return (Tooth)GetValue(ToothProperty); }
        set
        {
            SetValue(ToothProperty, value);
            NombrePieza.Text =   value.Id.Replace("_",String.Empty);
        }
    }
    public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI), new PropertyMetadata(0)); 

}

添加了Tooth依赖属性后,我的问题是出现了以下错误:

默认值类型与属性类型不匹配

这个错误具体是什么意思?目前设置DP的方法是什么?

2个回答

186

DP的默认值与您的类型不匹配。

更改

public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI),
                                         new PropertyMetadata(0));

to

public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI),
                                      new PropertyMetadata(default(Tooth)));

或者简单地不设置您的DP的默认值:

public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI));

2
非常感谢您的帮助。 - Juan Pablo Gomez
1
很高兴能帮助Juan.. :) - Rohit Vats

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接