[英]WPF Custom control dependency property: cannot be string type?
我試圖將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”,一切都將再次正常運行。
有人有解決這個謎的線索嗎?
您需要將默認值更改為null
,而不是0
,這是字符串的無效值:
new UIPropertyMetadata(null)
(或者您希望將其作為默認值的任何字符串值。)
我認為問題出在這里:
new UIPropertyMetadata(0)
你說該屬性的類型為string
,但它的默認值是int
0要么改變你想要作為默認(某些字符串值null
, string.Empty
,或別的東西),或刪除完整的參數-是可選的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.