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.
[...] 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 [...]
By: Refining the removal of strings from WPF dependency properties « The Agile Workshop blog on July 27, 2009
at 1:37 pm