Posts Tagged XML

Silverlight VisualState changes using DataBinding not code behind


Download
I hate the fact that I have to keep using code behind to trigger VisualState changes in my view.  Frequently I just want to change a visual state of a control based on the properties of the object to which the control is bound – such as making additional options visible or invisible, changing the mode of the display based on information stored in the model etc.

So I’ve come up with a control that helps!  The VisualStateController can be placed in the XAML for a control and be bound to a property of the databound object using its StateMode dependency property. 

  • If the property is a bool then two further properties OnState and OffState are used to determine the visual state of the control based on the value of the property.
  • If the property is an enum then the visual state will be set the the text string name of the enum value.
  • If the property is a string it will be used to directly set the visual state

Now changes causing normal binding updates will automatically trigger the visual state changes.

<VisualStateCtrls:VisualStateController StateMode="{Binding IsSelected}"
             OnState="Selected"
             OffState="Unselected"/>

<VisualStateCtrls:VisualStateController StateMode="{Binding IsResizable}"
             OnState="Sizers"
             OffState="NoSizers"/>

The VisualStateController binds automatically to the UserControl (or Control) that it is a child of.  You can put it inside any panel within the body of your UserControl’s XAML.

You can find the project and source code here.

If you want to achieve the same thing using triggers and a slightly more wordy approach, you can use blend and triggers – see here for details.

, , , , , , ,

5 Comments