WPF覆盖样式触发器的样式

问题描述 投票:-1回答:2

我有一个Radiobutton,其样式设置使其显示为ToggleButton,我想将其默认背景颜色设置为绿色,但是当它处于活动/检查状态时,我希望它改变颜色。在我下面的例子中,我希望它是蓝色的。无论我尝试什么,绿色永远不会被覆盖。我错过了什么?

按钮:

<RadioButton GroupName="Rating" Background="Green" Style="{StaticResource RatingToggleButtons}" x:Name="Normal" Content="Normal" Grid.Row="0" />

样式:

        <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>
wpf wpf-controls
2个回答
0
投票

简而言之,通过控件模板应用的背景具有优势,与通过Style(您的情况)设置的背景相比。因此您需要编辑控件模板。

  <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>

注意:代码未经过测试

请参阅:http://www.diranieh.com/NET_WPF/Properties.htm


0
投票

我错过了什么?

本地值优先于样式设置的值:https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-value-precedence

所以不要像这样设置本地值:

<RadioButton ... Background="Green" ... />

...你应该在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>

...并再次避免设置Background元素的RadioButton属性:

<RadioButton GroupName="Rating" Style="{StaticResource RatingToggleButtons}" x:Name="Normal" Content="Normal" Grid.Row="0" />
© www.soinside.com 2019 - 2024. All rights reserved.