Binding a DevExpress Grid Context Menu to a MVVM ViewModel Command

One of the things I sometimes wrestle with, is keeping to MVVM when working with DevExpress controls.

Today I was trying to bind the right click context menu on their grid control, to a command on my view model. I started off working from some of their example code which was event and code behind based. This lead me to the using the EventToCommand pattern, as didn’t want any code behind.

This is where the pain began! Firstly their BarButtonItem is derived from FrameworkContentElement, not FrameworkElement, which makes it incompatible with MVVM Light. I posted a question about this on stackoveflow which was answered with a great workaround.

However before I received that answer, I had already decided to just use the more vanilla System.Windows.Interactivity InvokeCommandAction which doesn’t have the limitation of only binding to FrameworkElements.

Again I ran into problems. It seems that the context menu’s from dev express are in their own visual tree, so I tried all sorts of bindings to try and get back to my ViewModel. None of which worked!

It was at this point that my colleague pointed out that, the menu items are actually buttons and have a command property. So all this wrestling with triggers was a complete waste of time – curses!

However, the binding to get back to the ViewModel is not at all obvious, as the DataContext on these popup menus is not what you might expect. Anyway it is possible, and the way to do it is as follows:

<dxg:TableView.RowCellMenuCustomizations>
    <dxb:BarButtonItem Name="deleteRowItem" Content="Delete"
        Command="{Binding View.DataContext.DeleteCommand}" />
</dxg:TableView.RowCellMenuCustomizations>

One thought on “Binding a DevExpress Grid Context Menu to a MVVM ViewModel Command

Leave a Reply