Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContextMenuOpening event not trigered

Tags:

c#

wpf

xaml

I have a button with a context menu, but I just can get the ContextMenuOpening event to triger.

<Button Name="a_button"
        ContextMenu="{StaticResource MyContextMenu}"
        ContextMenuOpening="MyContextMenu_Opening" >
</Button>

private void MyContextMenu_Opening(object sender, ContextMenuEventArgs e)
{
   // doesnt get here.
}

Any ideas how to make this work ?

Thanks.

like image 765
Adrian Avatar asked May 24 '26 11:05

Adrian


2 Answers

ContextMenuOpening event must be handled on an ancestor of the ContextMenu not on the ContextMenu itself. If you try handling it on the ContextMenu the event only fires when you right click once ContextMenu is already open.

like image 62
RichTurner Avatar answered May 27 '26 04:05

RichTurner


I've just checked your code and it works perfectly.

Here is my full xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ContextMenu x:Key="MyContextMenu">
            <MenuItem Header="Send" />
        </ContextMenu>
    </Window.Resources>
    <Grid>
        <Button Name="a_button"
                ContextMenu="{StaticResource MyContextMenu}"
            ContextMenuOpening="MyContextMenu_Opening" >
        </Button>
    </Grid>
</Window>

And *.cs:

    private void MyContextMenu_Opening(object sender, ContextMenuEventArgs e)
    {

    }
like image 26
Samich Avatar answered May 27 '26 02:05

Samich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!