tags:

views:

125

answers:

2

I am having trouble setting my ContentProperty to "Text". The error I am given is:

Invalid ContentPropertyAttribute on type 'MyType', property 'Text' not found.

The code behind looks like this:

[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);
            }
        }
    }

I have actually got it to work if I name the CLR property something other than the DependencyProperty - am I using DependencyProperties incorrectly?

+2  A: 

I thought it would be because typeof(LinkText) should be typeof(MyType), but I was able to get my test project to compile. Could you post the XAML file which is causing the error?

EDIT: Followup

Your problem is the two static methods you have in your code sample. Try removing those, and it should compile and work. The static methods only work with Attached Properties, not Dependency Properties.

micahtan
Sorry, that was just me cleaning up type names to make it easier to follow. Assume that it says typeof(MyType).
vanja.
You need to change the "new PropertyMetadata(false));" to a string value, such as "new PropertyMetadata(null));"
micahtan
Indeed, removing the GetText and SetText gets rid of the error.
rmoore
Thanks, that fixed it.
vanja.
+1  A: 

The error is coming from you're default value, set in:

... new PropertyMetadata(false) ...

Because the TextProperty is of type string, it expects a string for the default value. Try:

public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register(
        "Text",
        typeof (string),
        typeof(MyType), 
        new PropertyMetadata(String.Empty));
rmoore
Thanks, that explains the silly error I had, but not why ContentProperty("Text") fails.
vanja.