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



我正在尝试将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",我就会得到一个运行时错误,告诉我"无法创建在汇编程序中定义的MainControl实例CustomControl等....

然后我改回"int"类型,一切又正常运行了。

有没有人能解开这个谜团?

我认为问题在这里:

new UIPropertyMetadata(0)

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

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

new UIPropertyMetadata(null)

最新更新