简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM