我想更改点击按钮的背景

时间:2019-09-06 09:38:17

标签: wpf button triggers styles

我有两个按钮,button1和button2。最初,button1的背景将为白色,而button2的将为红色。

当我单击button2时,button2的背景应该变成白色,而button1应该变成红色。如果再次单击button1,在WPF中button1的背景应该变成白色,而button2应该变成红色。

为简短起见,它应该像切换按钮一样工作。

2 个答案:

答案 0 :(得分:0)

一个代码示例将是不错的选择,但这是一个示例(不使用mvvm)如何实现的示例

这是我的xaml:

    <StackPanel Width="300">
        <Button x:Name="button1" Background="White" Height="40" Click="button1_Click"/>
        <Button x:Name="button2" Background="Red" Height="40" Click="button2_Click"/>
    </StackPanel>

这是逻辑:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var temp = button1.Background;
            button1.Background = button2.Background;
            button2.Background = temp;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            var temp = button2.Background;
            button2.Background = button1.Background;
            button1.Background = temp;
        }

答案 1 :(得分:0)

private void Button1_Click(object sender, RoutedEventArgs e)
    {
        changeBackground();
    }

    private void Button2_Click(object sender, RoutedEventArgs e)
    {
        changeBackground();
    }

    private void changeBackground()
    {
        Button2.Background = Button2.Background == Brushes.Yellow ? Brushes.Red : Brushes.Yellow;
        Button1.Background = Button1.Background == Brushes.Yellow ? Brushes.Red : Brushes.Yellow;
    }