【问题标题】:WPF Custom control dependency property: cannot be string type?WPF自定义控件依赖属性:不能是字符串类型?
【发布时间】:2011-10-08 22:26:06
【问题描述】:

我正在尝试将 DependencyProperty 添加到 WPF 自定义控件。

在我保留 sn-p 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”,一切都再次正常运行。

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

【问题讨论】:

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

标签: c# wpf user-controls


【解决方案1】:

我认为问题出在这里:

new UIPropertyMetadata(0)

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

【讨论】:

    【解决方案2】:

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

    new UIPropertyMetadata(null)
    

    (或任何你想成为默认值的字符串值。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2012-08-29
      • 2011-12-21
      相关资源
      最近更新 更多