【问题标题】:How do I change the entire style of a button from code behind in realtime?如何从代码中实时更改按钮的整个样式?
【发布时间】:2011-11-23 22:54:13
【问题描述】:

我有一个会闪烁的按钮。

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

我想应该是这样的:

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>

我不想听到关于搜索这个问题的消息......

【问题讨论】:

  • 您检查过 DesktopWindow.Resources["GreenAlertButtonStyle"] 是否没有返回空值吗?
  • 是的,所有样式都存在,甚至设置都没有问题。
  • 明确我想清除旧样式并引入新样式(在明确设置背景之后)

标签: c# wpf button triggers background


【解决方案1】:

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

button1.ClearValue(BackgroundProperty);

【讨论】:

  • 这行得通。非常感谢您为我指明了正确的方向。
【解决方案2】:

试试:

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

【讨论】:

  • 没用,但谢谢。明确地说,我想清理旧样式,并引入新样式。
  • 会发生什么,FindResource 是否返回任何内容?
  • 是的,先生,我快速观察了返回的对象,它实际上是正确的样式。交换风格之前的时刻。我确实明确设置了按钮背景......我不确定这与它有什么关系。谢谢。
  • 您可以使用 StyleSelector (msdn.microsoft.com/en-us/library/…) 代替吗?
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2014-08-12
相关资源
最近更新 更多