rem
rem

Reputation: 17045

How to add condition to a WPF Context Menu?

How could I add some conditions changing list of MenuItems in a WPF Context Menu, depending on some attributes of clicked objects?:

<Grid.ContextMenu>
 <ContextMenu>
   <MenuItem  Name="EditStatusCm" Header="Change status" />
   ...
   <MenuItem ... />
 </ContextMenu>                   
</Grid.ContextMenu>

Upvotes: 2

Views: 5186

Answers (2)

MoominTroll
MoominTroll

Reputation: 2552

I find it much easier to make it in the code behind too. If this methods ok, a fairly easy piece of sample code:

ContextMenu cm = new ContextMenu();

cm.Items.Clear();
MenuItem mi;


mi = new MenuItem();
mi.Header = "myHeader";
mi.Click += new RoutedEventHandler(menuItemAlways_Click);
cm.Items.Add(mi); //this item will always show up

if(someCondition())
{
    mi = new MenuItem();
    mi.Header = "myConditionalHeader";
    mi.Click += new RoutedEventHandler(menuItemConditional_Click);
    cm.Items.Add(mi); //This item will show up given someCondition();    
}

cm.IsOpen = true;

Obviously a very simplistic example, but it illustrates how easy it is to do in code behind.

EDIT: In answer to your comment, here's the method I last used...

//raised upon an event, ie. a right click on a given control
private void DisplayContextMenu(object sender, MouseButtonEventArgs e)
{
     ContextMenu cm = GetAssetContextMenu() 
     //Method which builds context menu. Could pass in a control (like a listView for example)

     cm.IsOpen = true;
}

private ContextMenu GetContextMenu()
{  
     ContextMenu cm = new ContextMenu();
     //build context menu
     return cm;
}

That should make it a little clearer. Obviously the GetContextMenu() method will probably take some kind of parameter from which you can pull some kind of prorgam state - for instance if you are clicking on a listView you could then get a value for "listView.SelectedItem", from which you could build up the conditional contextMenu. I hope this is clear, I'm feeling a little foggy at the moment.

Upvotes: 4

Kamiikoneko
Kamiikoneko

Reputation: 825

I build my context menus in codebehind dynamically on the "ContextMenuOpening" Event. It works extremely well. This way I can look at all my variables in real time. I generally create a context menu that has everything I KNOW I'll need every time, then modify it in code behind before showing it. I'd post some code but it's proprietary.

Upvotes: 1

Related Questions