2009-06-25 61 views
1

我無法將我的ContentProperty設置爲「文本」。我給出的錯誤是:屬性「文本」中的ContentPropertyAttribute無效

'MyType'類型的屬性'Text'找不到ContentPropertyAttribute。

後面的代碼看起來是這樣的:

[ContentProperty("Text")] 
    public partial class MyType: UserControl 
    { 
     public MyType() 
     { 
      InitializeComponent(); 
     } 

     public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", 
                          typeof (string), 
                          typeof(MyType))); 

     public static string GetText(DependencyObject d) 
     { 
      return (string) d.GetValue(TextProperty); 
     } 

     public static void SetText(DependencyObject d, string value) 
     { 
      d.SetValue(TextProperty, value); 
     } 


     public string Text 
     { 
      get 
      { 
       return (string)GetValue(TextProperty); 
      } 
      set 
      { 
       SetValue(TextProperty, value); 
      } 
     } 
    } 

其實我已經知道了,如果我的名字比其他的DependencyProperty的CLR屬性的東西的工作 - 我使用DependencyProperties不正確?

回答

4

我認爲這應該是因爲typeof(LinkText)應該是typeof(MyType),但我能夠讓我的測試項目編譯。你能發佈導致錯誤的XAML文件嗎?

編輯:跟進

你的問題是你有兩個靜態方法的代碼樣本。嘗試刪除這些,它應該編譯和工作。靜態方法僅適用於附加屬性,不適用於相關屬性。

+0

對不起,這只是我清理類型名稱,使其更容易遵循。假設它說typeof(MyType)。 – 2009-06-25 04:03:36

+1

您需要更改「new PropertyMetadata(false));」爲一個字符串值,如「new PropertyMetadata(null));」 – micahtan 2009-06-25 04:10:55

1

錯誤是來自你是默認值,在設置:

... new PropertyMetadata(false) ... 

因爲TextProperty是字符串類型,它希望爲默認值的字符串。請嘗試:

public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register(
     "Text", 
     typeof (string), 
     typeof(MyType), 
     new PropertyMetadata(String.Empty));