WPF自定义控件依赖属性:不能是字符串类型?

时间:2011-10-08 22:26:07

标签: c# wpf user-controls

我正在尝试将DependencyProperty添加到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”更改为“string”,我就会收到运行时错误 “无法创建在程序集CustomControl等中定义的MainControl实例....

然后我改回“int”类型,一切都正常运行。

有人有解决这个谜团的线索吗?

2 个答案:

答案 0 :(得分:2)

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

new UIPropertyMetadata(null)

(或者您希望成为默认值的任何字符串值。)

答案 1 :(得分:2)

我认为问题在于:

new UIPropertyMetadata(0)

您说该属性的类型为string,但其默认值为int 0.要么将其更改为您想要的某个字符串值作为默认值{{1 <},null或其他内容),或完全删除该参数 - 它是可选的。