选中切换按钮时,更改切换按钮的背景颜色

时间:2022-11-20 14:08:00

I want to change the background color of a toggle button when the toggle button is checked and vice versa.

我想在选中切换按钮时更改切换按钮的背景颜色,反之亦然。

How can I achieve that?

我怎样才能做到这一点?

5 个解决方案

#1


21  

<ToggleButton Content="toggle">
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ToggleButton">
                        <Border BorderBrush="{TemplateBinding BorderBrush}" 
                                Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center"                  
                                              VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter> 
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

Nearly the same as Klaus ones, but using "TemplateBinding" instead of "TargetName". With the TemplateBinding, the ControlTemplate use the BorderBrush and Background from the ToggleButtons DefaultStyle. So the Trigger can set the ToggleButtons Background and with the Border this one will also be shown.

与Klaus几乎相同,但使用“TemplateBinding”而不是“TargetName”。使用TemplateBinding,ControlTemplate使用ToggleButtons DefaultStyle中的BorderBrush和Background。所以触发器可以设置ToggleButtons背景,并且边框也会显示这一个。

#2


6  

The best simple way to acheive this (and without any Blend and overriding 50 lines of XAML ;) is this way, i.e. using triggers :

实现这一目标的最简单方法(并且没有任何Blend和覆盖50行XAML;)就是这种方式,即使用触发器:

<Window x:Class="*.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <ToggleButton x:Name="tg" Height="20" Width="80">
        <ToggleButton.Style>
            <Style TargetType="{x:Type ToggleButton}">
                <Setter Property="Background" Value="Green"/>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="true">
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>

            </Style>
        </ToggleButton.Style>
    </ToggleButton>
</Grid>

Try this in the first place before going any further and see if it suit your needs

首先尝试这一点,然后再继续,看看它是否符合您的需求

#3


6  

Check this solution:

检查此解决方案:

<Grid>
<Grid.Resources>
  <Style x:Key="ToggleButtonStyle1" TargetType="{x:Type ToggleButton}">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type ToggleButton}">
          <Border HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="border" Padding="5,5,5,5" CornerRadius="5,5,5,5" Background="#FFBFACAC" BorderBrush="#FF000000" BorderThickness="1,1,1,1" SnapsToDevicePixels="True">
            <ContentPresenter x:Name="contentPresenter"/>
          </Border>
          <ControlTemplate.Triggers>
            <Trigger Property="IsChecked" Value="true">
              <Setter Property="Background" TargetName="border" Value="#FFC31010"/>
            </Trigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</Grid.Resources>

<ToggleButton Content="ToggleButton" Margin="25" Width="90" Height="45" Style="{StaticResource ToggleButtonStyle1}"/>

</Grid>

#4


5  

Do you have Expression Blend? It can be done easily by right-clicking on the ToggleButton and Select "Edit Template" then "Edit a copy...". From the template go to the "States" Tab and select the "Checked" state. Reset the background color, differing from the base state and your done.

你有Expression Blend吗?右键单击ToggleButton并选择“编辑模板”,然后选择“编辑副本...”即可轻松完成。从模板转到“状态”选项卡,然后选择“已检查”状态。重置背景颜色,与基本状态和完成时间不同。

See sample:

见样本:

<Window.Resources>
    <Style x:Key="ButtonFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <LinearGradientBrush x:Key="ButtonNormalBackground" EndPoint="0,1" StartPoint="0,0">
        <GradientStop Color="#F3F3F3" Offset="0"/>
        <GradientStop Color="#EBEBEB" Offset="0.5"/>
        <GradientStop Color="#DDDDDD" Offset="0.5"/>
        <GradientStop Color="#CDCDCD" Offset="1"/>
    </LinearGradientBrush>
    <SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/>
    <Style x:Key="ToggleButtonStyle" TargetType="{x:Type ToggleButton}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding Button.IsDefaulted}" SnapsToDevicePixels="true" Background="White">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates" ei:ExtendedVisualStateManager.UseFluidLayout="True">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0:0:0.5"/>
                                </VisualStateGroup.Transitions>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="CheckStates">
                                <VisualState x:Name="Checked">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Chrome">
                                            <EasingColorKeyFrame KeyTime="0" Value="Red"/>
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Unchecked"/>
                                <VisualState x:Name="Indeterminate"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <VisualStateManager.CustomVisualStateManager>
                            <ei:ExtendedVisualStateManager/>
                        </VisualStateManager.CustomVisualStateManager>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Microsoft_Windows_Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Grid x:Name="LayoutRoot">
    <ToggleButton Content="ToggleButton" HorizontalAlignment="Left" Height="36" Margin="116,131,0,0" VerticalAlignment="Top" Width="122" Background="White" Style="{DynamicResource ToggleButtonStyle}"/>
</Grid>

#5


1  

An alternative approach is to handle the the Checked and Unchecked events in XAML like this:

另一种方法是在XAML中处理Checked和Unchecked事件,如下所示:

<ToggleButton Checked="HandleChecked" Unchecked="HandleUnchecked" ... />

and in the code-behind:

并在代码隐藏中:

    private void HandleChecked(object sender, RoutedEventArgs e)
    {
        ToggleButton toggle = sender as ToggleButton;
        toggle.Background = new SolidColorBrush(Colors.Orange);
    }

    private void HandleUnchecked(object sender, RoutedEventArgs e)
    {
        ToggleButton toggle = sender as ToggleButton;
        toggle.Background = new SolidColorBrush(Colors.Transparent);
    }

#1


21  

<ToggleButton Content="toggle">
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ToggleButton">
                        <Border BorderBrush="{TemplateBinding BorderBrush}" 
                                Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center"                  
                                              VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter> 
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

Nearly the same as Klaus ones, but using "TemplateBinding" instead of "TargetName". With the TemplateBinding, the ControlTemplate use the BorderBrush and Background from the ToggleButtons DefaultStyle. So the Trigger can set the ToggleButtons Background and with the Border this one will also be shown.

与Klaus几乎相同,但使用“TemplateBinding”而不是“TargetName”。使用TemplateBinding,ControlTemplate使用ToggleButtons DefaultStyle中的BorderBrush和Background。所以触发器可以设置ToggleButtons背景,并且边框也会显示这一个。

#2


6  

The best simple way to acheive this (and without any Blend and overriding 50 lines of XAML ;) is this way, i.e. using triggers :

实现这一目标的最简单方法(并且没有任何Blend和覆盖50行XAML;)就是这种方式,即使用触发器:

<Window x:Class="*.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <ToggleButton x:Name="tg" Height="20" Width="80">
        <ToggleButton.Style>
            <Style TargetType="{x:Type ToggleButton}">
                <Setter Property="Background" Value="Green"/>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="true">
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>

            </Style>
        </ToggleButton.Style>
    </ToggleButton>
</Grid>

Try this in the first place before going any further and see if it suit your needs

首先尝试这一点,然后再继续,看看它是否符合您的需求

#3


6  

Check this solution:

检查此解决方案:

<Grid>
<Grid.Resources>
  <Style x:Key="ToggleButtonStyle1" TargetType="{x:Type ToggleButton}">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type ToggleButton}">
          <Border HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="border" Padding="5,5,5,5" CornerRadius="5,5,5,5" Background="#FFBFACAC" BorderBrush="#FF000000" BorderThickness="1,1,1,1" SnapsToDevicePixels="True">
            <ContentPresenter x:Name="contentPresenter"/>
          </Border>
          <ControlTemplate.Triggers>
            <Trigger Property="IsChecked" Value="true">
              <Setter Property="Background" TargetName="border" Value="#FFC31010"/>
            </Trigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</Grid.Resources>

<ToggleButton Content="ToggleButton" Margin="25" Width="90" Height="45" Style="{StaticResource ToggleButtonStyle1}"/>

</Grid>

#4


5  

Do you have Expression Blend? It can be done easily by right-clicking on the ToggleButton and Select "Edit Template" then "Edit a copy...". From the template go to the "States" Tab and select the "Checked" state. Reset the background color, differing from the base state and your done.

你有Expression Blend吗?右键单击ToggleButton并选择“编辑模板”,然后选择“编辑副本...”即可轻松完成。从模板转到“状态”选项卡,然后选择“已检查”状态。重置背景颜色,与基本状态和完成时间不同。

See sample:

见样本:

<Window.Resources>
    <Style x:Key="ButtonFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <LinearGradientBrush x:Key="ButtonNormalBackground" EndPoint="0,1" StartPoint="0,0">
        <GradientStop Color="#F3F3F3" Offset="0"/>
        <GradientStop Color="#EBEBEB" Offset="0.5"/>
        <GradientStop Color="#DDDDDD" Offset="0.5"/>
        <GradientStop Color="#CDCDCD" Offset="1"/>
    </LinearGradientBrush>
    <SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/>
    <Style x:Key="ToggleButtonStyle" TargetType="{x:Type ToggleButton}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding Button.IsDefaulted}" SnapsToDevicePixels="true" Background="White">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates" ei:ExtendedVisualStateManager.UseFluidLayout="True">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0:0:0.5"/>
                                </VisualStateGroup.Transitions>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="CheckStates">
                                <VisualState x:Name="Checked">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Chrome">
                                            <EasingColorKeyFrame KeyTime="0" Value="Red"/>
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Unchecked"/>
                                <VisualState x:Name="Indeterminate"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <VisualStateManager.CustomVisualStateManager>
                            <ei:ExtendedVisualStateManager/>
                        </VisualStateManager.CustomVisualStateManager>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Microsoft_Windows_Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Grid x:Name="LayoutRoot">
    <ToggleButton Content="ToggleButton" HorizontalAlignment="Left" Height="36" Margin="116,131,0,0" VerticalAlignment="Top" Width="122" Background="White" Style="{DynamicResource ToggleButtonStyle}"/>
</Grid>

#5


1  

An alternative approach is to handle the the Checked and Unchecked events in XAML like this:

另一种方法是在XAML中处理Checked和Unchecked事件,如下所示:

<ToggleButton Checked="HandleChecked" Unchecked="HandleUnchecked" ... />

and in the code-behind:

并在代码隐藏中:

    private void HandleChecked(object sender, RoutedEventArgs e)
    {
        ToggleButton toggle = sender as ToggleButton;
        toggle.Background = new SolidColorBrush(Colors.Orange);
    }

    private void HandleUnchecked(object sender, RoutedEventArgs e)
    {
        ToggleButton toggle = sender as ToggleButton;
        toggle.Background = new SolidColorBrush(Colors.Transparent);
    }