In the continuation of my ‘wow did not realize that existed in xaml’ series I wanted to post about how you can use DataTriggers bound to a value in your view model to trigger a visual state change.
Having the ability to trigger a state change via Binding is an awesome improvement over having to use the view’s codebehind as it is just another step towards total freedom of needing the code behind. If you were using the code behind to change state you would need to have a line similar to the following
VisualStateManager.GoToState(this, "ShowAuthenticationState", true);
So how do we trigger a state change via XAML and Binding?
First we need to reference the following namespaces in our XAML
Next we need setup our trigger in XAML as seen below
If you look at the XAML above there are 2 things to focus on
- I am setting up my DataTrigger to bind to a property called ScreenMode (you can of course bind to any property you want), I am also defining the value I want this to trigger off of, in my case Diagnostics
- I am defining the GoToStateAction for my DataTrigger. For my GoToStateAction I provide it the State Name of ‘ShowDebugState’, this is the name of one of the states I have defined inside my VisualStateManager (it is assumed you already know how to work with the VisualStateManager, if not there is plenty of information on StackOverflow
Once I have this XAML wired up correctly, each time my ScreenMode property changes to one of the defined values the corresponding ViewState will be set.
Till next time,
02-03-2014 6:45 AM