views:

72

answers:

2

Scenario: I have a (numeric) textbox, a button, and a label. When the button is clicked I'd like the label to "animate" to the numeric value in the textbox (like a spinning dial)

Given:

a) that animations in storyboards cannot have databindings (because they are not FrameworkElements) b) the lack of triggers in Silverlight

What is the best, and with least coupling of the view model to the view's storyboard, way to update the target animation value and start the animation when the button is clicked?

Note: The scenario is conceptual, so don't concentrate on the specifics of 'animating' numbers or anything

A: 

I recently had to solve a similar problem in an MVVM application. My problem was that I needed to animate a container's height from zero to auto. Since Auto is a dynamic value I recognized that the animation (or storyboard) would need to be built (or manipulated) on demand. The solution that I put in place involved using view code-behind to update and fire the animation.

This isn't the most MVVM-friendly approach; however, animations in WPF can be tricky in XAML. Since this solution is really just a workaround for a XAML limitation it seems okay to tie the code directly to the view. Likewise, if the views were mocked then there would be no framework elements to animate, so it really wouldn't make sense to place this code on the VM side.

Does anybody have a better approach?

Tony Borres
You could always add a AnimatedValue property to IViewInterface and have that get/set values from the animation itself, abstracting the animation from the VM. I'd still prefer a nicer way, though ;)
Richard Szalay
+2  A: 

If your goal is strictly to reduce the code-behind in the view I think that an attached behaviour on the Label would work for this. The attached behaviour on the label would expose the number to be animated to and when this number changes an animation (in code) would be run to animate from the old value to the new value.

One drawback is that your animation is now in code, unless you store a templated (just has fake values to start with) version of it in a resource file somewhere where you can load it as needed and replace the templated values.

This article from Josh Smith seems to be the authority on Attached Behaviours;

http://joshsmithonwpf.wordpress.com/2008/08/30/introduction-to-attached-behaviors/

Jacob
Yeah that's the direction I think thinking of taking. I do prefer having zero code in the code behind. Thanks!
Richard Szalay