Is it possible that the EventSetter of a Style runs side by side with another event handler?

1k views Asked by At

I have defined a Style for a Button in WPF. In that style, I want the button's background to be changed when it is clicked. For example:

<Style x:Key="TheButton" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Margin" Value="5"/>
    <EventSetter Event="Click" Handler="ChangeBackground"/>
</Style>

and in the code behind:

private void ChangeBackground(object sender, RoutedEventArgs e)
{
    var btn = sender as Button;
    if(btn != null)
        btn.Background = Brushes.SeaShell;
}

So this a general style that is applied to several Buttons, each performing a different job. Is it possible that the above event-handler could run along with the other event handler that is specified for each button when they are clicked?

If I specify a Click handler for a button that uses this style, does it override the EventSetter or the EventSetter has the higher priority?

2

There are 2 answers

5
AnjumSKhan On BEST ANSWER

Local value always takes precedence.

So, normal Click handler will fire followed by your EventSetter one.

0
gomi42 On

I would use some XAML magic to change the Background (but that's a matter of taste). The Click handler of the button works in parallel.

    <Style TargetType="Button">
        <Style.Triggers>
            <EventTrigger RoutedEvent="Click">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation To="#FFFF0000" Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>