2011-10-08 54 views
1

我正在尝试将DependencyProperty添加到WPF自定义控件中。WPF自定义控件依赖属性:不能是字符串类型?

一切都很好,直到我把代码生成由片段propdp:

namespace CustomControl 
{ 

    public partial class MainControl 
    { 
     public string MyProperty 
     { 
      get { return (string)GetValue(MyPropertyProperty); } 
      set { SetValue(MyPropertyProperty, value); } 
     } 

     // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty MyPropertyProperty = 
      DependencyProperty.Register("MyProperty", typeof(string), typeof(MainControl), new UIPropertyMetadata(0)); 

     public MainControl() 
     { 
      this.InitializeComponent(); 
     } 
    } 
} 

但只要我从“INT”到“串”改变类型,我得到一个运行时错误告诉 “不可能创造组装CustomControl等定义MainControl的实例....

然后我变回键入‘诠释’,一切运行正常再次。

是否有人有线索来解决这个谜?

+1

你确定你发布了导致错误的代码吗?该依赖项属性为我编译。你错过了什么? – slugster

回答

1

我认为问题就出在这里:

new UIPropertyMetadata(0) 

你说该属性的类型为string,但它的默认值是int 0.或者将其更改为默认的某个字符串值(null,string.Empty或其他),或者完全删除该参数 - 这是可选的。

+0

完美!现在它可以工作。感谢大家。 –

1

您需要将默认值更改为null,不0这是字符串值无效:

new UIPropertyMetadata(null) 

(或者任何字符串值,你想成为默认值)

相关问题