0

I have a project where I introduced a trigger for a button that changed the background color of the button when the mouse hovers it.

This is what it looks like:

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

I have no issues with this and it works as expected. These buttons are part of a numpad, so the same effect should happen when I press the number key on the keyboard.

This is the function that is reponsible for applying that effect on the button

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);
}

This also works fine. The problem is, the trigger stops working and hovering the button will have no effect. My assumption is that the trigger is somehow a child of the Background property and, by overriding it, I am overriding the trigger as well.

I might be able to derive from button and create a public function that simulates the hovering and call that from the HandleButtoneEffect function? But I would like to avoid this as much as possible

How can I solve this?

1 Answer 1

2

button.Background = new SolidColorBrush(Colors.LightGray); - this line assigns local value to dependecy property. Local value has high precedence and trigger cannot override it.

You can call ClearValue to restore style effect:

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);
}