如何在点击后更改按钮的背景?

时间:2018-04-13 20:13:09

标签: wpf xaml

点击后我必须更改按钮的背景。这是我的XAML代码:

<Style x:Key="BackColor"  TargetType="{x:Type Button}">
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="50"/>
        <Setter Property="Content" Value="SEND"/>
        <Setter Property="Background" Value="#FF06C548"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="FontFamily" Value="Global User Interface"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="17" Background="{TemplateBinding Background}">
                        <ContentPresenter
                            HorizontalAlignment="Center" 
                            VerticalAlignment="Center"  
                            Height="63"
                            Margin="192,17,177,10"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#FF0EAC44"/>
            </Trigger>
            <Trigger Property ="ClickMode" Value="Release">
                <Setter Property="Background" Value="#FF1B74CB"/>
            </Trigger>
        </Style.Triggers>
    </Style>

当我启动程序时,按钮不起作用,但设置了我需要的颜色。 我需要更改什么才能使我的按钮正常工作?如果我得到答案,我会很高兴。

2 个答案:

答案 0 :(得分:0)

我不喜欢代码,但这是一个解决方案:

XAML

<Button x:Name="Button1"
        Click="Button1_Click"
        Background="Red"/>

代码背后:

private void Button1_Click(object sender, RoutedEventArgs e)
{
    if (sender is Control control) control.Background = new SolidColorBrush(Colors.Blue);
}

我宁愿用绑定向您展示这一点,但它需要更多代码才能正确设置。

答案 1 :(得分:0)

您可以使用动画并将fillbehavior设置为holdend 也许它不是你想要的红色,但是:

    <Button>
        <Button.Style>
            <Style TargetType="Button">
            <Style.Triggers>
                <EventTrigger RoutedEvent="Button.Click">
                <BeginStoryboard>
                    <Storyboard>
                       <ColorAnimation To="Red" 
                                       Duration="0" 
                                       Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" 
                                       FillBehavior="HoldEnd"
                                                       />
                    </Storyboard>
                </BeginStoryboard>
                </EventTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>