如何在WPF中使用C#计算DataGrid选中行特定列的总和?
解决WPF DataGrid选中行特定列求和的问题
嘿,这个问题我之前也碰到过!WinForms和WPF的DataGrid设计思路差异挺大的,你报错的原因很明确:WPF里的DataGridRow确实没有Cells属性——因为WPF更推崇数据绑定优先,不像WinForms那样直接操作UI控件的元素。
下面给你两种解决方案,优先推荐第一种,更符合WPF的设计理念:
方案一:直接操作绑定的数据(推荐)
WPF的DataGrid.SelectedItems里存放的其实是你绑定的业务实体对象,而不是UI行控件。假设你的DataGrid绑定的是一个类似ObservableCollection<YourModel>的集合,其中YourModel有对应列的属性(比如Amount),那直接对选中的模型对象求和就好:
// 替换YourModel为你实际的模型类,Amount为对应列的属性名 decimal total = myGrid.SelectedItems.OfType<YourModel>().Sum(t => t.Amount);
这种方式的好处是完全遵循WPF的数据驱动UI理念,不用碰UI控件,代码更简洁可靠,后续维护也更方便。
方案二:通过UI控件获取单元格内容(不推荐,仅适用于未绑定数据的场景)
如果你的DataGrid没有绑定数据源,或者必须从UI层面获取值,可以通过DataGridRow的Item属性,或者借助辅助方法获取单元格内容:
首先写一个获取单元格的辅助方法:
private DataGridCell GetDataGridCell(DataGrid dataGrid, DataGridRow row, int columnIndex) { DataGridColumn column = dataGrid.Columns[columnIndex]; var cellContent = column.GetCellContent(row); return cellContent?.Parent as DataGridCell; }
然后遍历选中项计算总和:
decimal total = 0; foreach (var selectedItem in myGrid.SelectedItems) { // 获取选中项对应的DataGridRow DataGridRow row = myGrid.ItemContainerGenerator.ContainerFromItem(selectedItem) as DataGridRow; if (row == null) continue; // 获取指定索引的单元格 DataGridCell cell = GetDataGridCell(myGrid, row, 2); if (cell?.Content is TextBlock textBlock) { // 解析单元格文本为decimal类型(记得做异常处理) if (decimal.TryParse(textBlock.Text, out decimal cellValue)) { total += cellValue; } } }
注意:这种方式依赖UI控件的结构,一旦UI布局变化(比如列的类型从TextBlock改成其他控件),代码就可能失效,所以尽量优先用方案一。
内容的提问来源于stack exchange,提问作者Tamal Banerjee
相关产品推荐
相关产品推荐

