XAML has many very cool features, it seems I learn about new features every week. This week one of the features I found was how to use DataTriggers to control storyboards.
Why am I excited about this? Well I use the MVVM pattern when building any XAML based application and any time I needed to start a storyboard I would send a message to my view’s code behind from my view model to instruct the view to start the animation, this worked by always felt dirty to me. With DataTriggers I can simply use binding to start/stop my animations, this feels so much better to me.
So how does this work?
The first thing to show is our XAML which implements the DataTrigger
** Note **
To use Triggers and DataTriggers make sure you import the following namespaces
When looking at the above XAML there are 3 things of importance to point out
- The DataTrigger expects you to bind to your view model via the ‘Binding’ attribute. This works in the exact same manner as all other binding in XAML. Make sure you set the mode == TwoWay if the bound value is going to change
- The DataTrigger expects the Value attribute to be set. When setting this value you want to put in the property value which is expected to trigger the animation. In my case since I am binding to a boolean I am going to set this value to true. If you were binding to a string you would put what ever string value needed to trigger the storyboard
- The ControlStoryboardAction expects a the Storyboard attribute to be populated. In our case I am binding it to a local storyboard which is part of my DataTemplate. This binding works that same as all other StaticResource binding
When you have this setup correctly the changing of the ShowPresenceSelection property in my underlying viewmodel will trigger one of my Storyboards to play. I like this method because it feels better in an MVVM setup.
Till next time,
01-09-2014 6:10 AM