Wpf – Style a WPF Button on right mouse click

buttonstyleswpf

Is it possible to add a style trigger in WPF to a Button to determine whether or not the ContextMenu has opened?

If so, I'd like to color the background of the corresponding button if the contextmenu is opened.

Can't find a regular way to do it…

Best Answer

Here's a solution:

<Grid ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Button Grid.Column="1" Margin="5" Content="Button" x:Name="theButton">
        <Button.Background>
            <SolidColorBrush x:Name="BackgroundBrush" Color="LightGray" />
        </Button.Background>
        <Button.ContextMenu>
            <ContextMenu x:Name="contextMenu">
                <MenuItem Header="Option 1" />
                <MenuItem Header="Option 2" />
            </ContextMenu>
        </Button.ContextMenu>
        <Button.Triggers>
            <!-- This changed the color to red when the context menu is openning -->
            <EventTrigger RoutedEvent="Button.ContextMenuOpening">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="BackgroundBrush"
                                        Storyboard.TargetProperty="Color" Duration="0:0:0" To="Red" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
            <!-- This changed the color back to light gray when the context menu is closing -->
            <EventTrigger RoutedEvent="Button.ContextMenuClosing">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="BackgroundBrush"
                                        Storyboard.TargetProperty="Color" Duration="0:0:0" To="LightGray" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Button.Triggers>
    </Button>
</Grid>