Monday, May 16, 2011

Visual State Manager vs. Triggers in WPF

In my previous post I have explained about Visual State Manager you can read more about it here. After introducing Visual State Manager as new feature in WPF 4 many readers has question when to use Visual State Manager and when to use Triggers. In this post I tried to explain the usage of Visual State Manager and Trigger.

VisualStateManager vs. Triggers

As Visual State Manager introduced in WPF4 it doesn’t mean that Triggers are not going to use. Visual State Manager defines States of control and using each state you can customize the appearance of control.

For example Button has Normal, MouseOver, Pressed and Disabled states in common state group. Now assume you have created visual state for each of these states and you also want apply some custom appearance to button when button is set as default means IsDefault property is set to true. In this scenario you can specify Trigger along with Visual State Manager and apply some custom appearance to button when IsDefault property is set as True.

<Style x:Key="MyButton" TargetType="{x:Type Button}">
<Setter Property="Template">
<ControlTemplate TargetType="{x:Type Button}">
        <VisualStateGroup x:Name="CommonStates">
           <VisualState x:Name="Normal"/>
           <VisualState x:Name="MouseOver">
                      <EasingColorKeyFrame KeyTime="0" Value="#FF20F50E"/>
           <VisualState x:Name="Pressed" />
           <VisualState x:Name="Disabled"/>
        <Ellipse x:Name="ellipse" Fill="#FF0E0EF5" Stroke="Black"/>
       "{TemplateBinding HorizontalContentAlignment}"
          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        <Trigger Property="IsDefault" Value="True">
            <Setter TargetName="ellipse" Property="Opacity" Value="0.2"/>

<Button Content="Click Me!" IsDefault="True"
                Style="{StaticResource MyButton}"
                Height="100" Width="100" />


In above example you can see the opacity is applied to Button because IsDefault property is true. 

No comments:

Post a Comment