我正在尝试自定义我的 ToggleButtons,以便在选中时以绿色表示"is",在未选中时以红色表示“否”。
我创建了以下样式,它位于我的样式资源字典中。
<!-- ToggleButtons -->
<Style x:Key="YesNoToggleStyle" TargetType="ToggleButton">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="SpringGreen" />
<Setter Property="Content">
<Setter.Value>
<TextBlock Text="Yes"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Background" Value="Crimson" />
<Setter Property="Content">
<Setter.Value>
<TextBlock Text="No"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
这行得通……有点。如果 ToggleButton 是任一值中的最后一个,则它会正确显示。所有具有相同值的先前按钮都是空白的。高度也在缩小,但我用触发器上方的“高度” setter 修复了它。为了说明,当创建新记录时,它看起来像:
在我再次单击按钮 1、2、3 和 1 之后:
我最初从周围的网格中引用了样式:
<Grid>
...
<Grid.Resources>
<Style BasedOn="{StaticResource YesNoToggleStyle}" TargetType="{x:Type ToggleButton}" />
</Grid.Resources>
但是更改它以便每个 ToggleButton 单独引用样式 ( <ToggleButton Style="{StaticResource YesNoToggleStyle}" ... /> ) 并没有什么不同。
我看了Customizing the toggle state of a toggle button in wpf , 和 Override ToggleButton Style效果是一样的,但他们谈论的是外部图像,而我的问题都在 wpf 内。
我还看了第二个答案:i want to change backcolor of toggle button when toggle button ischecked and viceversa in WPF但是 a) 我只有 VS2012 附带的 blend + sketchflow 预览,b) 我是 blend 的菜鸟,无法从 Select the "Checked State" 获得至 Reset the Background Color答案中的说明(另外,如果此任务需要混合工具,我会感到惊讶)。
谁能告诉我如何让多个 ToggleButton 正确使用相同的样式?
请您参考如下方法:
这对我有用。 Dictionary1.xaml 中的某处:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="YesNoToggleStyle" TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}">
<Style.Triggers>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Background" Value="Crimson" />
<Setter Property="Content" Value="No"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="SpringGreen" />
<Setter Property="Content" Value="Yes"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
请注意,该样式基于 ToolBar.ToggleButtonStyle。
<Grid>
<Grid.Resources>
<ResourceDictionary Source="pack://application:,,,/Dictionary1.xaml"/>
</Grid.Resources>
<ItemsControl ItemContainerStyle="{StaticResource YesNoToggleStyle}">
<ToggleButton />
<ToggleButton />
<ToggleButton />
</ItemsControl>
</Grid>
