WPF获取DataGrid选中行shuju
时间: 2025-01-30 11:04:30 浏览: 75
### 如何在 WPF 应用程序中获取 DataGrid 控件的选中行的数据
为了实现在 WPF 应用程序中获取 `DataGrid` 控件的选中行的数据,可以采用多种方法。下面介绍一种常用的方法,即通过绑定和代码背后的方式。
#### 使用 XAML 定义 DataGrid 并设置选择模式
首先,在 XAML 文件中定义 `DataGrid` 控件,并为其指定合适的选择模式:
```xml
<DataGrid Name="dataGrid1"
SelectionMode="Single"
SelectionUnit="FullRow"
AutoGenerateColumns="False">
<!-- 列定义 -->
</DataGrid>
```
这里设置了 `SelectionMode` 属性为 "Single" 表示一次只能选择一行;而 `SelectionUnit` 设置成 "FullRow" 可以确保每次点击都会整行被选中[^2]。
#### 获取选中行的数据项
当用户选择了某一行之后,可以通过访问 `SelectedItem` 或者遍历 `SelectedItems` 来获得所选中的数据对象。对于单选情况下的操作如下所示:
```csharp
private void GetSelectedDataRow()
{
var selectedItem = dataGrid1.SelectedItem;
if (selectedItem != null)
{
// 假设 ItemsSource 是一个 ObservableCollection<Person> 类型,
// 那么此时 selectedItem 就会是 Person 类的一个实例。
Console.WriteLine($"Name: {((Person)selectedItem).Name}");
Console.WriteLine($"Age : {((Person)selectedItem).Age }");
}
}
```
这段 C# 代码展示了如何从 `SelectedItem` 中提取具体字段的信息并打印出来。注意这里的假设前提是 `ItemsSource` 被绑定了一个实现了 `INotifyPropertyChanged` 接口的对象列表[^3]。
另外,如果想要更灵活地处理多选的情况,则应该考虑使用 `SelectedItems` 属性代替 `SelectedItem`,并通过循环迭代每一个项目来进行相应的逻辑处理。
阅读全文
相关推荐




















