Posted by: Stephen Oakman | July 14, 2009

Removing the strings when registering Dependency Properties

We’ve just been doing some multi-touch WPF work. Well, when I say ‘we’ I really mean everyone else apart from me as it got into what I consider to be serious math of which I have very little (zero) knowledge. Anyway, I digress.

One of the things that has bugged me with WPF are the Dependency Properties, or at least the ugliness of them. An example is

public static readonly DependencyProperty CameraPostionProperty =
    DependencyProperty.Register("CameraPosition", typeof(Point3D), typeof(WorldViewModel));

What bug’s me most is the Register method. I don’t like the magic string which can get lost during a refactor and it would be far too easy to get the order of the type parameters the wrong way round. Just a misspelling of the string is enough for it to not work (which happens far more often than it should).

A much preferable syntax would be the following:

public static readonly DependencyProperty CameraLookDirectionProperty =
    DependencyPropertyHelper<WorldViewModel>.Register(x => x.CameraLookDirection);

With this syntax theirs no magic strings and no types to get mixed up.

This syntax is achieved with the code below:

public static class DependencyPropertyHelper<T>
{
    public static DependencyProperty Register<TR>(Expression<Func<T, TR>> action)
    {
        var member = (MemberExpression)action.Body;
        return DependencyProperty.Register(member.Member.Name, typeof(TR), typeof(T));
    }
}

Now we are taking the string from the member name itself and the order of the types is picked up correctly.

Advertisement

Responses

  1. [...] of strings from WPF dependency properties Following on from the previous post regarding removing the strings when registering Dependency Properties I wanted to fine tune it so we could remove the need for specifying the type we are defining the [...]


Leave a Reply

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

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

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.