MVVM Friendly Visual State Management with Windows Phone 7
27 May 2011
First, the problem. We want to be able to bind to and trigger an animation in the View from the View Model in a zero touch fashion. The use case I’m taking here is displaying a Progress Bar control and having it fade in/out, in this instance using a Visual State Manager.
There are plenty of pointers on how to do this with WPF and Silverlight, but not so many clear examples on Windows Phone.
So here’s our view, containing a PerformanceProgressBar (you are using this right?) which is animated off and on.
Now let’s take a look at the control’s code behind. What you will notice here is that we are in code setting up a Binding to a custom Dependency Property we have created. The source of the binding we have set to the view’s DataContext.
When the ProgressBarState property has changed, we handle this and call the VisualStateManager.GoToState method which will in turn trigger the animations to run, lovely.
Now to the View Model. I’m using Caliburn Micro, but any old INotifyPropertyChanged implementation will do.
Simply have a property called ProgressBarState and set it’s value with a line of code such as
I’ve used an enumeration to define the various Progress Bar States, i have two at this stage. I’m sure you can think of other scenarios where you might need more;)
And that’s it! Note that at no time does the View know about the View Model or vice versa, all is right with the world. There are of course better and more elegant ways to achieve this with WPF and later versions of Silverlight, but this is the best way I’ve found in the current release of Windows Phone (v7.0).