wpf 如何以编程方式更改选中/切换按钮的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29989603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:07:03  来源:igfitidea点击:

How to change the color of the checked/toggled button programatically

c#wpfxaml

提问by YWah

Let say I've a toggle button which is checked initially and the background color (the color when the button is checked/toggled, NOT the color of the button itself) is blue by default. How to change the background color of the checked/toggled button?

假设我有一个最初选中的切换按钮,默认情况下背景颜色(选中/切换按钮时的颜色,而不是按钮本身的颜色)为蓝色。如何更改选中/切换按钮的背景颜色?

For example:

例如:

if (myCondition == true)
    myToggleBtn.Background = System.Windows.Media.Brushes.Red;

The code above is just change the color of the toggle button itself, but I want to change the color checked/toggled button.

上面的代码只是更改切换按钮本身的颜色,但我想更改选中/切换按钮的颜色。

Updated

更新

<ToggleButton x:Name="Line1Btn" Content="Line 1" HorizontalAlignment="Left" Margin="8,84,0,0"
              VerticalAlignment="Top" FontFamily="Tahoma" FontSize="11" Height="26" Width="50"
              IsEnabled="True" BorderBrush="#FFC7C7C7" Click="Line1Btn_Click">
  <ToggleButton.Style>
    <Style TargetType="ToggleButton">
      <Setter Property="Background"> 
        <Setter.Value> 
          <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
            <GradientStop Color="#FFCFCFCF" Offset="0"/> 
            <GradientStop Color="White" Offset="1"/> 
          </LinearGradientBrush>
        </Setter.Value>
      </Setter>
      <Style.Triggers> 
        <Trigger Property="IsChecked" Value="True"> 
          <Setter Property="Background" Value="DarkSeaGreen"/> 
        </Trigger> </Style.Triggers>
    </Style>
  </ToggleButton.Style>
</ToggleButton>

Updated 2

更新 2

enter image description here

在此处输入图片说明

Generated from the same code, but show different results.

从相同的代码生成,但显示不同的结果。

回答by Nakul Chaudhary

enter image description hereYou can use this style for the button

在此处输入图片说明您可以将这种样式用于按钮

               <Style TargetType="Button">
                <Setter Property="Foreground" Value="Blue"></Setter>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Foreground" Value="Red" /> 
                    </Trigger>
                </Style.Triggers>
            </Style>
               <Style TargetType="Button">
                <Setter Property="Foreground" Value="Blue"></Setter>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Foreground" Value="Red" /> 
                    </Trigger>
                </Style.Triggers>
            </Style>