当切换按钮被选中时更改背景颜色。

5
我正试图区分单击时切换按钮的状态。我有下面的代码片段。
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="OnOffToggleImageStyle" TargetType="ToggleButton">
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Background" Value="DimGray"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <ToggleButton Height="60" Content="Text" Style="{StaticResource OnOffToggleImageStyle}">
        </ToggleButton>
    </Grid>
</Window>

然而,当在样式中将IsChecked值设置为“True”时,此方法无效。 当设置为false时,它有效。
我想知道原因。 有任何答案!
1个回答

5
运行您的代码样本时,似乎样式与“切换按钮”的“chrome”(即按钮的原始样式)发生了冲突。
在这种情况下,最好重写“ToggleButton”的模板以按您所需的方式运作。下面是一个丑陋的示例:
<Style x:Key="myToggleButton" TargetType="{x:Type ToggleButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate>
        <Border x:Name="outer"
        BorderBrush="White"
        BorderThickness="2"
        Opacity=".9"
        Background="Transparent">
          <Border x:Name="inner"
          Margin="8"
          BorderThickness="0"
          Background="{
            Binding Background, 
            RelativeSource={RelativeSource TemplatedParent}}">
            <Grid x:Name="container">
              <Grid.RowDefinitions>
                <RowDefinition Height="2*"/>
                <RowDefinition/>
              </Grid.RowDefinitions>
              <TextBlock x:Name="display"
              Grid.Row="1"
              Text="{Binding Content, RelativeSource={
                RelativeSource TemplatedParent}}"
              Foreground="White"
              FontSize="11"
              FontFamily="Segoe UI"
              FontStyle="Normal"
              FontWeight="Normal"
              Margin="8,0,0,4"
              HorizontalAlignment="Left"
              VerticalAlignment="Bottom"/>
            </Grid>
          </Border>
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="ToggleButton.IsChecked" Value="True">
            <Setter TargetName="outer" Property="Background" Value="LightBlue"/>
            <Setter TargetName="outer" Property="BorderBrush" Value="Transparent"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

lbbster,你能告诉我在哪里找到原始togglebutton样式的代码吗?先谢谢了。 - Nerielle
@nerielle 迟来的回复,但如果有人搜索这个: https://msdn.microsoft.com/fr-fr/library/cc296245%28v=vs.95%29.aspx - eka808
谢谢,这真的帮了我很多。现在我的问题是,是否有文档显示每个基本元素(ToggleButton,Button等)的“ chrome”长什么样子? - EdwardM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接