Tuesday, June 22, 2010

Wpf Animations and Mvvm

One of the many topics I have been wanting to look into in more detail lately has been how animations specifically work with MVVM.  It seems to be more complicated than it first appears on the surface.  If the state of a controller (ViewModel) changes then the view follows suit by binding to a state property or at least using a DataTrigger etc.  The View either changes immediately to the new visual state (like show/hiding a panel) or beginning an animation to show or hide something. But what if you wanted to play the animation storyboard and once it finished then allow the state to change?

One of the best MVVM resources I have read recently is Josh Smith's Advanced MVVM mini-book.

In this book he talks about this very topic among many other relevant topics under the heading Advanced MVVM.

You can download his source code for this book here. Its a rather simple but cool game.


Chapter 5 of Josh's book talks about this very topic.  The challenge is to be able to trigger a series of animations each one starting only when the other has completed.  Each transition could take an unknown period of time. I won't steal his book's thunder, just a reference so the an example of a good answer can be found.

If I was to approach this, my simplistic approach simply would be to expose events on the controller for each phase passing through any necessary information as an EventArgs subclass. This isn't as elegant, but would still be suitable.  The challenge is effectively communicating back to the controller the view has completed its animation transition.  This could be achieved one of two ways:
1) Use the completed event on the storyboard to call a method on the controller.
2) Pass a delegate as a event args parameter which is called when on the storyboard complete event is raised.

The real question here is: Is there a better way using Blend4 with visual states? Like most things in life the question to one answer simply leads to at least 2 more questions.  I suspect not, as a visual state cannot help you define dynamic storyboards that change.

No comments:

Post a Comment