Search code examples
wpfmouseevent-bubblingelementhost

Bubble mouse event from WPF to WinForms


I have WPF control hosted inside a WinForms control using ElementHost. The WinForms control has a context menu. I want to show the context menu when user right click on the WPF control. How can this be done? It seems mouse event is not bubbled from WPF to WinForms.


Solution

  • it is not automatically bubbled up, as you might have handled it in the WPF control in the first place. However, you can easily add this yourself.

    In your WPF user control, expose an event that you trigger on right mouse up:

        public event Action ShowContext;
    
        private void rectangle1_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (ShowContext != null)
            {
                ShowContext();
            }
        }
    

    Then in your winforms control with element host you can use it like so:

        public UserControl1 WpfControl { get; set; }
    
        public Form1()
        {
            InitializeComponent();
    
            WpfControl = new UserControl1();
            WpfControl.ShowContext += () => contextMenuStrip1.Show(Cursor.Position);
            elementHost1.Child = WpfControl;
         ....