views:

641

answers:

2

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>
+1  A: 

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.

Kamiikoneko
Thanks for the idea!
rem
+3  A: 

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.

MoominTroll
Thanks for the code example! Could you, please, give idea how to connect this generated Context Menu to a particular object on a page?
rem
Should I create empty ContextMenu in XAML and build Menu Items in "ContextMenuOpening" event handler?
rem
Thank you! Could you please tell, why Context Menu, opening on MouseRightButtonDown event, stays open for a second or so, just blinks. What should I do in addition to "cm.IsOpen = true;"?
rem
Use PreviewRightMouseButtonUp instead (or give Kamiis ContextMenu event a go).
MoominTroll
Yes, it works, thanks!
rem