Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM retrieve datagrid selected rows

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.

like image 768
wipindipy10 Avatar asked Jun 28 '12 07:06

wipindipy10


1 Answers

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);
like image 118
Roberto Conte Rosito Avatar answered Oct 15 '22 21:10

Roberto Conte Rosito