简体   繁体   中英

How to change button background when button is clicked using WPF

This is as close as I can get to changing a button background in WPF when I click on the button.

<Trigger Property="IsPressed" Value="true">
    <Setter TargetName="_Border" Property="Background" Value="#313131" />
</Trigger>

But using Property="IsPressed" will change the background color for as long as it is pressed. I would like it to stay the color after it is pressed.

This is my styling


<Style x:Key="Button_No_Light_Gray" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="_Border" Background="Red" Margin="1" BorderBrush="#202020">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter TargetName="_Border" Property="Background" Value="#313131" />
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter TargetName="_Border" Property="Background" Value="#313131" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

I have looked at other questions similar to this on Stack overflow but their solutions have not worked for me. The background color of the _Border must be changed.

I have found a solution on a different way, by Click event.

First, you need to add this into you XAML code, as shown below

<Button Content="Content"  Width="70" Height="50" Name="BtnColor" Click="BtnColor_Click"/>

Then, in the Code Behind you:

private void BtnColor_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            btn.Background = btn.Background == Brushes.Red ? (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFDDDDDD") : Brushes.Red;
        }

Note: This will change the color of the button back and forth, by every click. Hope that is not a problem.

If you don't want that, simply set the value of BrushConverter to the one that you need. For example if you want it to stay red, just go

ConvertFrom("#FFFF0000") instead of what it was.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM