点击WPF更改按钮背景

本文关键字:按钮 背景 WPF 点击 | 更新日期: 2023-09-27 18:18:57

我在侧板上有一组按钮。我想更改已点击按钮的背景。我试过使用style.trigger和我能想到的唯一属性是IsPressed,但这并没有多大帮助,因为它改变了一秒钟的背景(直到按钮按下[duh])。

这是我试过的代码:

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

我能想到的另一种方法是为每个带有datatrigger的按钮创建单独的样式,因为我有一个属性可以随着按钮的选择而改变,但这似乎有点过头了。我该如何突出显示已点击的按钮?

点击WPF更改按钮背景

这种触发器在满足条件时运行,然后效果消失。为了设置好,而不是一会儿看一下这个

<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>

因为IsPressed不是一个RoutedEvent,所以你可以使用

 <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>
<UserControl.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Green"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Background" Value="Red"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>
<Grid RenderTransformOrigin="0.578,0.503">
    <Button Width="100" Height="50" Margin="265,265,435,135"/>
    <Button Height="50" Margin="400,202,302,198"/>
</Grid>