Changing the background of a WPF button on a click

I have a set of buttons on the sidebar. I want to change the background of the button that the button was clicked on. I tried to do this with style.trigger , and the only property I could think of was IsPressed , but that doesn't help much since it changes the background for a second (until the button is pressed [duh]).

This is the code I tried:

 <Style.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background" Value="SlateGray" /> <Setter Property="Foreground" Value="White"></Setter> </Trigger> </Style.Triggers> 

Another way I could think of is to create an individual style for each button using a datatrigger , since I have a property that changes with the choice of the button, but it seems like overkill. Any idea how I can highlight the button that was pressed?

+1
source share
1 answer

This type of trigger fires when your condition is met, and then the effect disappears. To establish a good, not some time, take a look at this

 <Button Content="Content" Background="Red"> <Button.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="CadetBlue"/> </Storyboard> </BeginStoryboard> </EventTrigger> </Button.Triggers> </Button> 

Since IsPressed is not a RoutedEvent, you can use this

  <Button Content="Content" Background="Red"> <Button.Style> <Style TargetType="Button"> <Style.Triggers> <Trigger Property="IsPressed" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="CadetBlue"/> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> 
+8
source

Source: https://habr.com/ru/post/1243249/


All Articles