WPF MVVM retrieves selected data rows

I have a checkered DataGrid using this code 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.

+6
source share
1 answer

since you are using the MVVM pattern, you can declare a ViewMode as follows:

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

After that, in your datagrid you can declare a binding like this:

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

In your code, you can use the SelectedItem property to get the currently selected datagrid row. If you mean "checked" strings, you can request your observable collection:

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

Source: https://habr.com/ru/post/919215/


All Articles