WPF MVVM 如何获取 DataGrid 中被选中的行

9

我有一个DataGrid,其中使用我在互联网上找到的以下代码实现了复选框。

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

但是,我该如何获取选定的行?我正在使用WPF MVVM。


3
请在给问题点踩时添加一条评论,让提问者知道为什么他们的问题被点踩。谢谢。 - Simon Dugré
1个回答

14

由于您正在使用MVVM模式,您可以像这样声明一个ViewModel:

public class MyViewModel 
{
    public ObservableCollection<Prototype> Items { ... }
    public Prototype SelectedItem SelectedItem { ... }
}
在你的datagrid中,可以以如下方式声明绑定:
<DataGrid ItemSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"... />
在你的代码中,你可以使用 "SelectedItem" 属性来获取当前选择的数据网格行。否则,如果你指的是“已选中”的行,则可以查询你的可观察集合:
var selectedRows = ViewModel.Items.Where(i => i.IsSelected);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接