2011-10-08 58 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) 

(或者任何字符串值,你想成爲默認值)

相關問題