2

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?

1
  • 1
    Are you sure youhave posted the code that causes the error? That dependency property compiles for me. Have you missed something? Commented Oct 8, 2011 at 22:52

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.