I have a datagrid that potentially can have many rows. As the user right clicks one of the rows, I need to show a context menu for each of the rows and perform an action (same action but different data item according to the current selected row) when the user clicks the option.
What is the best strategy for this?
I’m fearing that a ContextMenu for each row is overkill even though I’m creating the menu using the ContextMenuOpening event, sort of a “lazy load” for the context menu. Should I only use one ContextMenu for the datagrid? But with this I would have some more work regarding the click event, to determine the correct row, etc.
As far as I know, some of the actions will be disabled or enabled depending on the row, so there is no point in a single
ContextMenufor aDataGrid.I have an example of the row-level context menu.
The
DataGridmust have a binding to a list of view models with commands:The context menu is created in the resources collection of the
UserControland I think there is only one object which is connected with datagrid rows by reference, not by value.Here is another example of
ContextMenufor aCommandinside aMainViewModel. I suppose thatDataGridhas a correct view model as theDataContext, also the CommandParameter attribute must be placed before the Command attribute:Models:
But there is a problem that
MenuItemisn’t displayed as a disabled item ifCanExecutereturns false. The possible workaround is using aParentModelproperty inside theItemModel, but it doesn’t differ much from the first solution.Here is example of above-described solution:
And MenuItem in XAML will be simplier: