Binding WPF Data Grid SelectedItems in a MVVM application



Binding WPF Data Grid SelectedItems in a  MVVM  application

Binding cannot be done directly on SelectedItems Property of  WPF Data Grid because its read-only.

But if you just want to pass all selected items of a DataGrid back to view model, it can be done via following workaround

Suppose you have a button to and a DataGrid

Button performs certain action on all selected items from DataGrid

All selected rows from data grid can be send to view model via command parameter

<Button Content="Action Selected" Margin="5,5,5,5"
       Command="{Binding Path=ActionCommand}"   
       CommandParameter="{Binding ElementName=ItemsGrid, Path=SelectedItems}"/>


<DataGrid x:Name="ItemsGrid" ItemsSource="{Binding Path=Items}"  
          SelectionMode="Extended"
          CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True">
</DataGrid>

Another approach/ more sophisticated approach would be driving from WPF DataGrid and creating a custom DataGrid, I will try and do it coming weekend