WPF: Building ContextMenu “On Fly”

April 14, 2008

         Let’s say we creating application which have to display context menu built “on fly”. By saying “On Fly” I mean we actually have to create context menu object and populate in with items, according to state which is right for mouse click coordinates. This WPF application also hosts Winforms user controls. So we have to support both platforms, and here one possible way to accomplish that:

 

Handiling Winforms:

     Winform controls are hosted inside WindowsFormsHostWPF control. I expected it will fire standard WPF events such as ContextMenuOpening, but it doesn’t. So I subscribed to Winform control’s “MouseUp” and this is how I handling it:

 

ContextMenu cm = new ContextMenu();

//here Context populated by items

 

cm.PlacementTarget = sender as UIElement;

cm.IsOpen = true;

 

Handling WPF: 

That’s all. For WPF window, you can choose 2 possible solutions:

  1. Handle right click as well (this is what I did in my sample).
  2. Handle ContextMenuOpening event. If you choose this path, then instead of setting “IsOpen” property ‘true’, assign “ContextMenu” property by created ContextMenu object. Example:

 

private void OnContextMenuOpening(object sender, ContextMenuEventArgs e)

{

  ContextMenu cm = new ContextMenu();

  //here Context populated by items

 

  FrameworkElementfe = e.Source as FrameworkElement;

  fe.ContextMenu = cm;

}

 

Complete sample get from here.

Entry Filed under: WPF. Tags: , .

Leave a Comment

hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Top Posts

Tags

.NET addin app.config ArrayList bug CAB Configuration ConfigurationManager ConfigurationSection ContentControl ContextMenu CTime; DateTime custom keys DataBinding DataContext Data templates debugging equals gethashcode GUI Hashtable interlocked Invoke lock lock free memcpy MFC multithreading multithreading; lock free override performance SCSF serialization Smart Client Software Factory Styles System.Configuration unsafe virtual functions Visual Studio wait free WinAPI WinForms WinForms\WPF Integration World of Warcraft World of Warcraft; Addon

Archives