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:
- Handle right click as well (this is what I did in my sample).
- 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: ContextMenu, WinForms\WPF Integration.
Trackback this post | Subscribe to the comments via RSS Feed