Visual States in XAML Templates

The Silverlight and desktop WPF implementations of Templates use the same syntax and programming model for describing the tree of objects that make up the control body, but differ in how they describe dynamic changes of the template.  In desktop WPF, this is done using Triggers...for example, a trivial Button Template might look like:

        <ControlTemplate x:Key="MyButton" TargetType="Button">


            <Border x:Name="Back" Background="{TemplateBinding Background}">





                <Trigger Property="IsMouseOver" Value="true">

                    <Setter Property="Background" TargetName="Back" Value="Red"/>




As I've explained in previous posts, time and resource constraints left us unable to implement Triggers in the Silverlight 2 timeframe.  We were left then with the problem of delivering the same functionality reusing as much existing code from Silverlight as possible.  The design we came up with evolved from deconstructing Triggers in WPF and thinking about the basic pattern anew.  The fundamental recognition is that a Trigger actually has two parts:  a condition (IsMouseOver == true) and a body (the Setters and other actions in more complex examples). 

The body of the Trigger changes the appearance of the Control...this is what we call a Control State, or a Visual State.  The latter term is more precise, as the Control also has a Logical State which consists of the values of all its properties.  The Condition in a Trigger maps the Logical State (IsMouseOver) to a Visual State (Background = Red). 

In Silverlight we had two existing, fully implemented things we could use to describe Visual States...a collection of Setters like a Style, or a Storyboard.  Since Storyboards allow you to create Visual States that are animated, we choose the second, more flexible construct.  The Condition we left to the Control code itself...and thus we get the Silverlight Beta 1 "Parts and States" model (Parts are an already existing concept from desktop WPF).   Looking forward to unification of the desktop and web Template models, we can imagine a world where a Trigger in the Template contains a GoToState action that triggers the Storyboard instead of the boilerplate code each control must currently write. 

In Silverlight Beta 2, we have taken some steps in that direction, and formalized the concept of a Visual State.  More soon.