Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to dynamically generate ContextMenu

I have ListBox (with SelectionMode=Extended) that has multiple items and I want to to add context menu feature. The problem is how to dynamically create context menu based on some conditions. Eg. I'd like to show regular context menu if only one item is selected but to show other context menu (eg. with some new items added) when more than one item is selected. In addition, I'd like to create third kind of context menu if among the selected item is at least one that has some property set. Etc... there can be multiple conditions like these.

Basically I need to dynamically generate context menu right after user has right-click the mouse button but just before the menu is actually shown. Is this possible?

like image 691
matori82 Avatar asked Feb 09 '13 01:02

matori82


1 Answers

I am aware that this is an old question. It seems that there is a very simple answer which solves the OP's original problem in a MVVM scenario, because the ContextMenu class supports binding via the ItemsSource property.

Hope it helps someone encountering this.

XAML

      <ContextMenu ItemsSource="{Binding Path=ItemList, UpdateSourceTrigger=PropertyChanged}">
      </ContextMenu>

In the ViewModel, you can modify the "ItemList" property dynamically according to the current application state.

like image 99
nepdev Avatar answered Sep 21 '22 08:09

nepdev