Live Chat Icon For mobile
Live Chat Icon

WPF FAQ - Context Menu

Find answers for the most frequently asked questions
Expand All Collapse All

It’s possible that you have a list of commands that you simply want to bind to a context menu. You can do so as follows.

For example, if you have list of custom commands, each of this type:

public class MyCommand
public Name{get; set;}
public Command{get; set;}

Then you can bind a list containing the above items to a ContextMenu as follows:

    <Style TargetType='{x:Type MenuItem}'>
      <Setter Property='Command' Value='{Binding ContextMenuItemCommand}'/>

<ContextMenu ItemsSource={StaticResource myList}></ContextMenu>

Instead of setting up event handlers on all the MenuItems you can listen to those events as they bubble up to the context menu as follows:



Or you can setup the same thing in code as follows:

menuItem1.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(MnItem_Click));

The event handler would then be something like:

private void MnItem_Click(object sender, RoutedEventArgs e)
	MenuItem item = e.Source as MenuItem;

This example uses the ContextMenuService.ShowOnDisabled property to show the context menu for a disabled button.


<Button Height='30' Content='Disabled Button' IsEnabled='False' 
      <MenuItem Header='Item 1'/>
      <MenuItem Header='Item 2'/>
      <MenuItem Header='Item 3'/>


To automatically close the context menu after a set time interval, you can use a Timer and send an Esc keystroke after the desired time interval as shown.


private void timer1_Tick(object sender, System.EventArgs e)

private void contextMenu1_Popup(object sender, System.EventArgs e)
//set interval to 5 seconds
timer1.Interval = 5000;


Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.