WPF changing button background on click

◇◆丶佛笑我妖孽 提交于 2020-01-09 08:03:15

问题


I have a set of buttons in a side panel. I want to change the background of the button that has been clicked. I have tried to do that using style.trigger and the only property I could think of is IsPressed, but that doesn't help that much since it changes the background for a second (till the button is pressed [duh]).

This is the code I've 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 was creating individual style for each button with a datatrigger since I've a property that changes with the selection of the button, but that seems like a overkill. Any idea how can I highlight a button that has been clicked?


回答1:


This kind of trigger runs when your condition is fulfilled and then the effect disappears. In order to set for good instead of a while 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>


来源:https://stackoverflow.com/questions/25414686/wpf-changing-button-background-on-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!