Thursday, August 22, 2013

WPF - The dependency property is already registered


This is the error you will face when you are copy pasting the code to write dependency property. JJoking…That is not the reason of this error. But I have received it when I copy pasted dependency property code from one of the site.
You will land up in this error when you have dependency property written in following way –
public readonly DependencyProperty SelectedItems2 =
            DependencyProperty.Register("SelectedItems2", typeof(string), typeof(ListBox), new PropertyMetadata(null));

What is missing here? - STATIC keyword.
The problem lies in a way you register your dependency property. You should not register in the default constructor of the class, but in static constructor or initialize it at the time of declaration and preceding with Static keyword. Best way to write dependency property without error is code snippet. Type ‘propdp’ then press tab twice. And then customize the property as per your requirement. This is how you can avoid this error; avoid learning of dependency property syntax and save time.
public static readonly DependencyProperty SelectedItems2 =
            DependencyProperty.Register("SelectedItems2", typeof(string), typeof(ListBox), new PropertyMetadata(null));

Hope this helps.
Cheers…
Happy Properting!!!

4 comments:

  1. this really helps a lot, i will not copy paste the code again :) (joking)

    ReplyDelete
  2. I was struggling with this problem... could not find the exact reason, this was it, thanks a lot.

    ReplyDelete
  3. I write exactly same still its give me same exception property already registerd

    ReplyDelete