Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

Archive for April 2008

Dependency Property Annoyance

leave a comment »

While I’m in the blogging mood, can you spot the bug with the code below?

public static readonly DependencyProperty MyCoolProperty = DependencyProperty.Register("MyCool",
    typeof(double),
    typeof(MyCoolObject),
    new FrameworkPropertyMetadata(0));

It’s not an obvious problem and unless you’re really into WPF it’s even less obvious. The problem is that when setting the default value of 0 (zero). The framework rightfully assumes it should be an int, but it will throw an exception when it tries to assign it to the associated dependency property during runtime. Why? Because it cannot implicitly convert the int type to a double type.To fix it you need to declare the dependency property like (notice the 0.0 in place of the 0):

public static readonly DependencyProperty MyCoolProperty = DependencyProperty.Register("MyCool",
    typeof(double),
    typeof(MyCoolObject),
    new FrameworkPropertyMetadata(0.0));
Advertisements

Written by Tom

April 4, 2008 at 11:53 am

Posted in .Net, C#, Gotcha, WPF