Implement Multiselect in WPF DataGrid in proper WPF way with Multiselect Behavior and without any code behind
In this article you will see how to implement multiselect in WPF DataGrid in proper way when you are following MVVM pattern. In this article you will see how to implement a behavior to your DataGrid so that we can achieve multiselect.
Behaviors are introduced with Expression Blend, to encapsulate pieces of functionality into a reusable component. These components can then be attached to controls to give them an additional behavior.
Multiselect is something which is like a must have feature in any control which displays multiple items, but unfortunately it is not straight forward in WPF when you are an MVVM developer. We need to attach a multiselect behavior to controls like DataGrid in order to get multiselect working.
Problem it addresses
In DataGrid, the property “SelectedItems” does not have an accessible setter. So we need alternate ways to get the list of selected items.
Here you need to add reference to System.Windows.Interactivity. If you have installed blend, then it is available in C:\Program Files (x86)\Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\WPF.
Using the code
- Add reference to System.Windows.Interactivity
- Add DataGrid to your xaml.
- create view model with a public property called SelectedItems.
- Create multiselect behavior as shown below.
- Now add this behavior to DataGrid. Also don’t forget to make SelectionMode=”Extended”. This will help you to select row by pressing Ctrl key.
Point of interest
If you have multiple DataGrid, then you need multiple Multiselect behaviors, one way to avoid this is by creating switch in MultiselectBehavior.