2009-06-25 43 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));