Tuesday, September 6, 2011

'x' was already registered by 'y' in Silverlight and WPF

So, I've had the extreme pleasure of working with a lot of Silverlight recently -- and my code in WPF had never been tested with multiple controls (stupid me).  When I did, I got all kinds of errors about properties not being set correctly, and eventually, after commenting out enough, I received the error

"'X' was already registered by 'Y.'"

So looking deeper, I notice it always happens on the second element.  Weird.  Looking further, I notice that my DependencyProperty pattern is basically declared at a private-instance level, i.e.:
DependencyProperty TitleProperty = DependencyProperty.Register("Title"typeof(string), typeof(SomeControl), new PropertyMetadata(string.Empty));
In Silverlight, this isn't a big deal.  In WPF, it's a deal-breaker.  It appears that Silverlight can automatically handle instance-level dependency properties (or more likely, translating bad code into them).  In WPF, it's not as forgiving and needs to be prefaced by:
public static readonly 
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title"typeof(string), typeof(SomeControl), new PropertyMetadata(string.Empty));

With that, everything works again and my Silverlight code doesn't break either.

Interesting difference between WPF and Silverlight, for sure.

No comments:

Post a Comment