WPF MVVM: find out which context menu was clicked

I am trying to use the MVVM pattern to write a WPF application. I am using a WPF data grid (from the toolbox) that lacks an autofiltration function. Therefore, I want to implement it. I added a context menu to the column header template, it has a MenuItem called "Filter", which should actually call the filter method.

So, I installed the MenuItem command as the appropriate delegate command that goes into the ViewModel. The problem is that I need to pass information about the actual column that was right-clicked! If I had not used MVVM, I would have executed an event handler that would receive the sender argument (MenuItem), then I would have found its parent (ContextMenu), and then its parent provided me with a column. But how can I achieve the same here? How to transfer the sender to my team? Can this be done using ComandParameter?

I really do not want to use additional complex templates to achieve such a simple task. In the end, MVVM should simplify development, not the other way around ...

+3
source share
3 answers

Can you pass the value of the column header as a command parameter and use it to get column information in the ViewModel?

+1
source

You can try some relative source magic, but it might be easier for you if you can have a different ViewModel to which you are attached for each title, for example HeaderViewModelItem. From there, you simply fire the delegate companion in your HeaderViewModelItem, rather on your large view model.

I used this model with pretty good success. Gets a little dance dance.

0
source

- , , . , - DataContext , -

<MenuItem CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=DataContext}" />

GridViewColumnHeader , , - .

0
source

Source: https://habr.com/ru/post/1713102/


All Articles