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">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimationUsingKeyFrames
Storyboard.TargetProperty=
"(Shape.Fill).(SolidColorBrush.Color)"
Storyboard.TargetName="ellipse">
<EasingColorKeyFrame KeyTime="0" Value="#FF20F50E"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed" />
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Ellipse x:Name="ellipse" Fill="#FF0E0EF5" Stroke="Black"/>
<ContentPresenter
HorizontalAlignment=
"{TemplateBinding HorizontalContentAlignment}"
RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsDefault" Value="True">
<Setter TargetName="ellipse" Property="Opacity" Value="0.2"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Button Content="Click Me!" IsDefault="True"
Style="{StaticResource MyButton}"
Height="100" Width="100" />
Output
In above example you can see the opacity is applied to Button because IsDefault property is true.
No comments:
Post a Comment