问题
I have a Radiobutton, which has styling set to make it appear as a ToggleButton, and I want to set its default background color to green, but when it is active/checked i want it to change color. In my example below I'd like it to be blue. No matter what I try the green color never gets overridden. What am I missing?
Button:
<RadioButton GroupName="Rating" Background="Green" Style="{StaticResource RatingToggleButtons}" x:Name="Normal" Content="Normal" Grid.Row="0" />
Style:
<Style x:Key="RatingToggleButtons" TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource MahApps.Metro.Styles.MetroToggleButton}">
<Setter Property="Margin" Value="5 5 5 5" />
<Setter Property="MinWidth" Value="100"/>
<Setter Property="MinHeight" Value="50"/>
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
回答1:
In Short,background applied via control template has upper hand, compared to background set via Style (your case.) So you need to edit control template.
<RadioButton.Template>
<ControlTemplate TargetType="{x:Type ButtonBase}">
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" TValue="#FF838383"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</RadioButton.Template>
note : code not tested
Refer to : http://www.diranieh.com/NET_WPF/Properties.htm
回答2:
What am I missing?
The fact that local values take precedence over values set by styles: https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-value-precedence
So instead of setting a local value like this:
<RadioButton ... Background="Green" ... />
...you should define the default value in the Style
:
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Background" Value="Green"/>
<Setter Property="Margin" Value="5 5 5 5" />
<Setter Property="MinWidth" Value="100"/>
<Setter Property="MinHeight" Value="50"/>
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
...and again avoid setting the Background
property of the RadioButton
element:
<RadioButton GroupName="Rating" Style="{StaticResource RatingToggleButtons}" x:Name="Normal" Content="Normal" Grid.Row="0" />
来源:https://stackoverflow.com/questions/52108986/wpf-override-style-from-a-style-trigger