如何实时更改代码背后的整个按钮样式?

时间:2011-09-23 20:02:58

标签: c# wpf button triggers background

我有一个闪烁的按钮。

我希望在资源字典闪烁时更改整个按钮样式。

我认为会是这样的:

DesktopWindow.AlertButton.Style = (Style)DesktopWindow.Resources["GreenAlertButtonStyle"];

但这不起作用。我该怎么做呢?我不能简单地改变背景颜色(虽然这是我真正想做的)因为我想保留触发器。当我立即更改按钮的背景时,鼠标悬停触发器停止工作....

按钮:

    <Style TargetType="Button" x:Key="BaseAlertButtonStyle">
    <Setter Property="ToolTip" Value="Show Alert List"/>
    <Setter Property="Effect" Value="{DynamicResource dropShadow}" />
    <Setter Property="Background" Value="{DynamicResource AlertButtonBackground}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch">
                    <Border CornerRadius="5" x:Name="ButtonBorder" Margin="0,0,0,0"
                            VerticalAlignment="Stretch" BorderThickness="0"
                            BorderBrush="#ffffff" Padding="0"
                            Background="{TemplateBinding Background}"
                            HorizontalAlignment="Stretch">
                        <Image x:Name="alertImage">
                            <Image.Source>
                                <BitmapImage UriSource="/resources/alertIcon.png" />
                            </Image.Source>
                        </Image>
                    </Border>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="Background" Value="{DynamicResource ButtonRolloverBackground}"/>
                    </Trigger>
                </ControlTemplate.Triggers>                    
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我不想听到有关搜索此问题的信息....

2 个答案:

答案 0 :(得分:1)

尝试:

DesktopWindow.AlertButton.Style = FindResource("GreenAlertButtonStyle") as Style;

答案 1 :(得分:0)

明确设置背景后,您必须清除BackgroundProperty然后设置新样式。

button1.ClearValue(BackgroundProperty);