I have a WPF button as such
<Button Name="HelloWorldButton"
Width="100"
Height="100"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Style="{StaticResource TileButton}">
Hello world
</Button>
Using WPF styling I have applied a style template as shown below
<Style x:Key="TileButton" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="focusRect"
Margin="-6"
BorderThickness="6">
<ContentPresenter />
<Border.BorderBrush>
<SolidColorBrush x:Name="focusRectBrush" Color="Transparent" />
</Border.BorderBrush>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Duration="0"
Storyboard.TargetName="focusRectBrush"
Storyboard.TargetProperty="Color"
To="Red" />
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimation Duration="0"
Storyboard.TargetName="focusRectBrush"
Storyboard.TargetProperty="Color"
To="White" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I would now like to apply the MouseOver VisualState
programmatically. I have looked through the HelloWorldButton.Style
property and cannot see any obvious way of achieving this.
Note: Obviously I understand that it would be trivial to programmatically add a border to the button directly without using the declared XAML style sheet, however in my scenario this is not a viable approach.
Finally worked it out.
The code I was looking for was as simple as