from Bob Bartholomay
A recent question on the Silverlight forums reminded me of an issue any MVVM fanboy will face sooner or later: “Is it possible to start an animation (StoryBoard in the XAML) from the ViewModel”?
One of the major tenets of MVVM is “separation of concerns” in that the View is not supposed to know about the ViewModel (among other things). The View’s DataContext gets set on its instantiation and from there on out all it knows is that parts of it are databound to something somewhere.
Animations/Storyboards happen in the View. For example, the transition from one ViewState to Another. So how do you get a StoryBoard to begin or cause ViewState change when a Property in the ViewModel changes or is of a particular value? The poster wanted a MVVM solution that follows the mantra: “no (read little as possible) code behind for the View”.
I’ve solved this previously by using Routed Events fired from the ViewModel in response to a Command associated with a UI Control. What I hadn’t solved was how to get these View changes purely on changes to the data in the ViewModel.
I scoured the Web and found more questions than solutions but eventually identified a number of approaches (some better than others):
- ICommands and RoutedEvent
- Using an IView interface
- ICommand and CLR Events
- Using a StoryboardManager
- Using DataTriggers