在代码中更新切换按钮的外观(在 xaml 中设置样式)不起作用

Update toggle button's appearance (with style set in xaml) in code not working

我的应用程序中有几个平面切换按钮,它们继承了如下相同的样式:

<Style x:Key="TButtonStyle" BasedOn="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}" TargetType="ToggleButton">
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="VerticalAlignment" Value="Top"/>
    <Setter Property="FontFamily" Value="Tahoma"/>
    <Setter Property="FontSize" Value="11"/>
    <Setter Property="Height" Value="26"/>
    <Setter Property="Width" Value="50"/>
    <Setter Property="BorderBrush" Value="#FFC7C7C7"/>
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                <GradientStop Color="#FFCFCFCF" Offset="0"/>
                <GradientStop Color="White" Offset="1"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderThickness" Value="2"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="False">
            <Setter Property="BorderThickness" Value="1"/>
            </Trigger>
    </Style.Triggers>
</Style>

在我做了某些更新后(例如,当一个过程被执行时,TButton.Background = System.Windows.Media.Brushes.Blue,它起作用了),我想把切换按钮改回原来的样子,但是它不管用。这是我将样式改回原始样式的方法:

TButton.Style = (Style)FindResource("TButtonStyle");

有什么解决这个问题的建议吗?是因为"StaticResource"吗?

如果您在进行处理时在代码中分配背景颜色,它的优先级高于您的样式。

清除背景颜色属性以重新设置

TButton.ClearValue(Button.BackgroundProperty);