WPF DataGrid: Binding DataGridColumn visibility to ContextMenu MenuItems IsChecked (MVVM)

后端 未结 6 636
不思量自难忘°
不思量自难忘° 2020-12-23 23:45

I want to control DataGrid column visibility through a ContextMenu available to the user by right-clicking the column header. The ContextMenu

6条回答
  •  孤独总比滥情好
    2020-12-24 00:33

    I've been looking for a generic, XAML (i.e., no code-behind), automatic and simple example of a column chooser context menu that binds to a WPF DataGrid column header. I've read literally hundreds of articles, but none of them seem to do exactly the right thing, or they're no generic enough. So here's what I think is the best combined solution:

    First, put these in the resource dictionary. I'll leave it as an exercise to the reader to write the Visibility/Boolean converter to ensure the checkboxes check when the column is visible and vice-versa. Note that by defining x:Shared="False" for the context menu resource, it'll get instance-specific state which means that you can use this single template/resource for all your datagrids and they'll all maintain their own state.

    
    
    
        
            
        
    
    
    
    
    
        
    
    

    Then define the DataGrid as follows (where OrdersQuery is some data source exposed by the View-model):

    
    
      
    
    
    

    This will give you the following:

    1. A context menu bound to the column headings which acts as a column chooser.
    2. A context menu bound to the items in the grid (to perform actions on the items themselves - again, the binding of the actions is an exercise for the reader).

    Hope this helps people who've been looking for an example like this.

提交回复
热议问题