martin.p
martin.p

Reputation: 363

WPF Custom control dependency property: cannot be string type?

I'm trying to add a DependencyProperty to a WPF custom control.

Everything is fine until I keep the code generate by the snippet 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();
        }
    }
}

But as soon as I change the type from "int" to "string", I got a runtime error which tells "Impossible to create an instance of MainControl defined in assembly CustomControl etc....

Then I change back to type "int" and everything run again properly.

Does somebody have a clue to fix this mystery?

Upvotes: 2

Views: 4607

Answers (2)

svick
svick

Reputation: 244777

I think the problem lies here:

new UIPropertyMetadata(0)

You're saying that the property has a type of string, but its default value is the int 0. Either change that to some string value that you want as a default (null, string.Empty, or something else), or remove that parameter completely – it's optional.

Upvotes: 3

Martin Liversage
Martin Liversage

Reputation: 106826

You need to change the default value to null, not 0 which is an invalid value for string:

new UIPropertyMetadata(null)

(Or whatever string value you want to be the default value.)

Upvotes: 2

Related Questions