WPF如何获取DataGrid的选中行

在DataGrid中加入这一行

<MouseBinding
   Command="{Binding OpenWindowCommand}"
   CommandParameter="{Binding ElementName=NewPlanDataGrid, Path=SelectedItem}"
   Gesture="LeftDoubleClick" />
</DataGrid.InputBindings>

然后ViewModel中委托OpenWindowCommand命令,如图所示obj就是选中的当前行的对象。

WPF DataGrid获取选中号,你可以通过以下步骤操作: 1. 首先,需要在一个依赖属性或者方法中绑定DataGrid的IsSelected属性到一个集合,这样每当你择或取消择一,这个集合就会更新。 ```xaml <DataGrid ItemsSource="{Binding YourDataSource}" AutoGenerateColumns="False"> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/> </Style> </DataGrid.RowStyle> </DataGrid> ``` 2. 创建一个方法来跟踪选中及其索引。可以使用`ObservableCollection<YourDataType>`的`CollectionChanged`事件来监听变化,并在事件处理程序中保存选中信息,例如: ```csharp private ObservableCollection<DataGridViewRow> selectedRows = new ObservableCollection<DataGridViewRow>(); public int SelectedRowIndex { get { return selectedRows.Count > 0 ? (int)selectedRows.Last().Tag : -1; } } private void DataContext_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach(DataGridViewRow row in e.NewItems) { if(row.IsSelected) selectedRows.Add(row); } } else if(e.Action == NotifyCollectionChangedAction.Remove) { foreach(DataGridViewRow row in e.OldItems) { if(selectedRows.Contains(row)) selectedRows.Remove(row); } } } ``` 在这里,`selectedRows`集合保存了所有被选中,而`SelectedRowIndex`则返回最后一条被选中的索引。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值