I am trying to change the Background
color of my Button when the user clicks it. I am using triggers to achieve it.
My XAML is:
<UserControl.Resources>
<Style x:Key="myBtnStyle" TargetType="{x:Type Button}">
<!--VerticalAlignment="Top" VerticalContentAlignment="Top" Background="Blue" HorizontalAlignment="Right"
Height="24" Width="25" FontSize="16" FontWeight="Bold" -->
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="VerticalContentAlignment" Value="Top" />
<Setter Property="Background" Value="Blue" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Height" Value="24" />
<Setter Property="Width" Value="25" />
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="Bold" />
<Style.Triggers>
<Trigger Property="Button.IsMouseOver" Value="true">
<Setter Property="Background" Value="Yellow" />
</Trigger>
</Style.Triggers>
</Style>
<!--
<ControlTemplate x:Key="btnTemplate" TargetType="{x:Type Button}">
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True" >
<Setter Property="Background" Value="Cyan" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate> -->
</UserControl.Resources>
<Button DockPanel.Dock="Right" Style="{StaticResource myBtnStyle}" Name="btnVert" Click="btnVert_Click"
Margin="10,10,10,0" ToolTip="Vertical" Content="V" />
I tried various settings, but couldn't get the Background color changed on the Button when mouse is clicked. Also referred various sites - MSDN, SharpCorner, CodeProject and many others too. Couldn't get where am I going wrong?
How to get the Background
color changed of Button on clicked event?
Thanks.
In WPF, you can animate objects by using Storyboard.
In this situation, you need to use
EventTrigger
withStoryboard
, because [Source
]:Example:
Here
Storyboard
defined in resources, which defines the colorButtonBrush
, which is set at theClick
event. For more information, please see:MSDN: EventTrigger
Edit
Yes,
EventTrigger
can be used in the template like this:As for the possibility of contact to the other buttons through one
Storyboard
, you can do so:In this case, you just need to specify
TargetName
for every Button, when you click on the first Button, the color of the remaining changes to defaultBlueViolet
: