Tom Goff's .Net Musings

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: