During my experiments with WPF, I sometimes encountered a recurring operation that required too much code (in my opinion.) So I did what every well-informed developer would: I encapsulated it into helper classes. Here are some of them:

Dependency Helpers

DependencyProperty GetDependencyProperty(DependencyObject o, string propertyName)
Retrieves a dependency property according to its name.

Binding Helpers

void UpdateSourceDefaultProperty(DependencyObject o)
If you ever set UpdateSourceTrigger of a Binding to Explicit, you may have felt it was a bit tedious to create the BindingExpression every time and call the UpdateSource() method. I realized that in many of the cases, the dependency property I’m updating is actually the default (or the content) property that the control author tagged using an attribute. So, instead of:

BindingExpression exp = BindingOperations.GetBindingExpression(TheTextBox, TextBox.TextProperty);

We get:


Storyboard Helpers

public static void Reverse(Storyboard storyboard)
Reverses the To and From properties of each linear AnimationTimeline in a Storyboard.

public static Storyboard GetReversed(Storyboard storyboard)
Clones the Storyboard and reverses it.

public static TAnimation AddLinearAnimation<TAnimation, T>(Storyboard storyboard, PropertyPath path, T? from, T? to, Duration duration)
Creates and adds a linear AnimationTimeline to a Storyboard. This one also saves quite a few lines. For example, instead of:

DoubleAnimation anim = new DoubleAnimation(from, to, new Duration(TimeSpan.FromSeconds(1)));
Storyboard.SetTargetProperty(anim, new PropertyPath(Control.OpacityProperty));

We get:

AddLinearAnimation<DoubleAnimation, double>(story, new PropertyPath(Control.OpacityProperty), from, to, new Duration(TimeSpan.FromSeconds(1)));

The one drawback of all of these methods is the use of Reflection. Had DoubleAnimation inherited from LinearAnimationBase<double> (see previous post) the use of Reflection could have been spared. 🙂

Attachment: Helpers.rar

Tagged with:

Comments are closed.

Set your Twitter account name in your settings to use the TwitterBar Section.