WPF MVVM retrieve datagrid selected rows

wipindipy10 picture wipindipy10 · Jun 28, 2012 · Viewed 15.7k times · Source

I have a DataGrid with checkbox implemented on it using this code which I found on the internet.

<my:DataGrid.RowHeaderTemplate>
  <DataTemplate>
    <Grid>
      <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:DataGridRow}}}" />
    </Grid>
  </DataTemplate>
</my:DataGrid.RowHeaderTemplate>

But, how can I get the selected rows? I am using WPF MVVM.

Answer

Roberto Conte Rosito picture Roberto Conte Rosito · Jun 28, 2012

since you're using the MVVM pattern you can declare a ViewMode like this:

public class MyViewModel 
{
    public ObservableCollection<Prototype> Items { ... }
    public Prototype SelectedItem SelectedItem { ... }
}

After, in your datagrid, you can declare binding in this way:

<DataGrid ItemSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"... />

In your code you can use the "SelectedItem" property to get current selected datagrid row. Else if you mean "checked" rows, you can query your observable collection:

var selectedRows = ViewModel.Items.Where(i => i.IsSelected);