【问题标题】:Mouse Hover trigger not working after changing background color programmatically以编程方式更改背景颜色后鼠标悬停触发器不起作用
【发布时间】:2020-06-25 06:24:00
【问题描述】:

我有一个项目,我为一个按钮引入了一个触发器,当鼠标悬停时它会改变按钮的背景颜色。

这就是它的样子:

<Window.Resources>
    <Style x:Key="ButtonStyleDefault" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="White"/>
        <Setter Property="Margin" Value="1.8"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Focusable" Value="False"/>
        <Setter Property="IsTabStop" Value="False"/>
        <Setter Property="FontWeight" Value="DemiBold"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}" BorderThickness="1" BorderBrush="DarkGray">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="LightGray"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

我对此没有任何问题,它按预期工作。 这些按钮是小键盘的一部分,所以当我按下键盘上的数字键时应该会出现同样的效果。

这是负责在按钮上应用该效果的函数

private async void HandleButtonEffects(Button button)
{
    if (button is null) {
        return;
    }

    button.Background = new SolidColorBrush(Colors.LightGray); 
    await Task.Delay(80)
            .ConfigureAwait(true);
    button.Background = new SolidColorBrush(Colors.LightGray);
}

这也很好用。问题是,触发器停止工作并且悬停按钮将无效。 我的假设是触发器在某种程度上是 Background 属性的子属性,通过覆盖它,我也覆盖了触发器。

我也许可以从按钮派生并创建一个模拟悬停的公共函数并从HandleButtoneEffect 函数中调用它?但我想尽可能避免这种情况

我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf xaml button triggers


    【解决方案1】:

    button.Background = new SolidColorBrush(Colors.LightGray); - 此行将本地值分配给依赖属性。本地值具有高 precedence 并且触发器无法覆盖它。

    您可以拨打ClearValue恢复样式效果:

    private async void HandleButtonEffects(Button button)
    {
        if (button is null)
        {
            return;
        }
    
        button.Background = new SolidColorBrush(Colors.LightGray);
        await Task.Delay(80).ConfigureAwait(true);
        button.ClearValue(Button.BackgroundProperty);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 2013-10-07
      • 2015-09-29
      • 2010-12-25
      • 1970-01-01
      相关资源
      最近更新 更多