Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContextMenuOpening event not firing in WPF?

Tags:

c#

mvvm

wpf

I have a resource dictionary inside which I have a context menu:

<ResourceDictionary x:Class="MyApp.Components.MyContextMenu"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyApp"
                    xmlns:components="clr-namespace:MyApp.Components">
    <ContextMenu ContextMenuOpening="OnContextMenuOpening">

and the resource dictionary XAML has this code behind:

using System;
using System.Windows;
using System.Windows.Controls;

namespace MyApp.Components
{
    public partial class MyContextMenu : ResourceDictionary
    {
        public MyContextMenu()
        {
            InitializeComponent();
        }  

        void OnContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            Console.WriteLine("here i am!");
        }
    }
}

The log is not appearing. I wonder why the event is not firing or getting to the right place -- is the problem because I have wrapped the context menu inside this resource dictionary?

Update: Interestingly if I remove the code-behind function, I get an error during compilation:

does not contain a definition for 'ContextMenu_OnContextMenuOpening' and no extension method 'ContextMenu_OnContextMenuOpening' accepting a first argument of type 'MyApp.Components.MyContextMenu' could be found (are you missing a using directive or an assembly reference?)

Update 2: Looks like that both Console.WriteLine and Debug.WriteLine produce output, but only "randomly" and especially when I'm clicking near the bottom of the item. Some sort of collision detection not working maybe?

like image 648
Tower Avatar asked May 16 '12 16:05

Tower


1 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 70
RichTurner Avatar answered Oct 13 '22 00:10

RichTurner