WPF中如何从DataGridCellInfo获取Item的Name字段值?
WPF DataGrid获取Item中Name字段的正确方法
问题出在DataGridCellInfo.Item的类型是object,直接访问Name或者用索引器会因为类型不匹配失败,得先把它转换成你的实体类型,下面是几种可行的方式:
- 强转成实体类(推荐,有编译检查)
假设你的数据项是Project类(替换成你实际的实体类型):
private void ProjectsDatagrid_SelectionChanged(object sender, MouseButtonEventArgs e) { if (ProjectsDatagrid.SelectedCells.Count == 0) return; var selected = ProjectsDatagrid.SelectedCells[0]; // 方式1:as关键字加空判断 var project = selected.Item as Project; if (project != null) { var foo = project.Name; // 这里使用foo } // 方式2:C#7+模式匹配(更简洁) if (selected.Item is Project project2) { var foo2 = project2.Name; // 这里使用foo2 } }
- 反射获取(适用于不知道具体实体类型的场景)
如果没法确定Item的具体类型,可以用反射读取属性值:
private void ProjectsDatagrid_SelectionChanged(object sender, MouseButtonEventArgs e) { if (ProjectsDatagrid.SelectedCells.Count == 0) return; var selected = ProjectsDatagrid.SelectedCells[0]; var nameProp = selected.Item.GetType().GetProperty("Name"); if (nameProp != null) { var foo = nameProp.GetValue(selected.Item)?.ToString(); // 这里使用foo } }
- 动态类型(不推荐,无编译检查)
用dynamic跳过编译类型检查,但运行时如果Item没有Name属性会报错:
private void ProjectsDatagrid_SelectionChanged(object sender, MouseButtonEventArgs e) { if (ProjectsDatagrid.SelectedCells.Count == 0) return; var selected = ProjectsDatagrid.SelectedCells[0]; dynamic item = selected.Item; var foo = item.Name; // 这里使用foo }
另外注意:一定要先判断SelectedCells的数量大于0,避免索引越界报错。
内容的提问来源于stack exchange,提问作者Dunno
相关产品推荐
相关产品推荐

