如何遍历WPF工具包Datagrid的行

我有下一个代码,我定义了一个名为dgQuery的WPF工具包数据网格控件; 我用数据集的信息填充了这个,然后我在dgQuery中插入了一个新的复选框列来检查/取消选中某些行,我展示了部分C#代码:

dgQuery.DataContext = dS.Tables[0]; DataGridTemplateColumn cbCol = new DataGridTemplateColumn(); cbCol.Header = "Opc"; FrameworkElementFactory factory = new FrameworkElementFactory(typeof(CheckBox)); Binding bind = new Binding("IsSelected"); bind.Mode = BindingMode.TwoWay; factory.SetValue(CheckBox.IsCheckedProperty, bind); DataTemplate cellTemplate = new DataTemplate(); cellTemplate.VisualTree = factory; cbCol.CellTemplate = cellTemplate; dgQuery.Columns.Insert(0, cbCol); 

在检查/取消选中dgQuery行的新复选框列后,我将单击一个按钮,仅将我检查的行保存到数据库中。 问题是,我如何开发循环来读取dgQuery的所有行以及让我知道哪些行选中/取消选中复选框的条件? 请帮我举个例子。

谢谢!!

这将在您的数据网格中返回一个“行”

 public IEnumerable GetDataGridRows(Microsoft.Windows.Controls.DataGrid grid) { var itemsSource = grid.ItemsSource as IEnumerable; if (null == itemsSource) yield return null; foreach (var item in itemsSource) { var row = grid.ItemContainerGenerator.ContainerFromItem(item) as Microsoft.Windows.Controls.DataGridRow; if (null != row) yield return row; } } 

在wpf datagrid中,行是ItemSource.items …没有Rows属性!

希望这可以帮助…

  var row = GetDataGridRows(dataGrid1); /// go through each row in the datagrid foreach (Microsoft.Windows.Controls.DataGridRow r in row) { DataRowView rv = (DataRowView)r.Item; // Get the state of what's in column 1 of the current row (in my case a string) string t = rv.Row[1].ToString(); } 

不确定这是否有用,因为它采用与您开始时不同的方法,而不是直接使用网格,您可以将其绑定到具有每列属性的对象的ObservableCollection。 如果在对象中为“Selected”添加bool属性并将checkbox列绑定到它,则可以随时查询该集合以查找当前选择的内容,如下所示:

  List selectedItems = new List(from memberEntity in _memberEntities where memberEntity.Selected == true select memberEntity); //now save selectedItems to the database... 

因此,MemberEntity是一个类,它为网格中的每个列都有一个属性,包括一个名为Selected的复选框列的bool。 _memberEntities是MemberEntity实例的ObservableCollection。 网格的ItemSource属性绑定到_memberEntities,并且其每个列的Binding属性都绑定到MemberEntity中的属性,假设Selected和Name是MemberEntity中的属性:

       
 //Looping thought datagrid rows & loop though cells and alert cell values var row = GetDataGridRows(DataGrid_Standard); /// go through each row in the datagrid foreach (Microsoft.Windows.Controls.DataGridRow r in row) { DataRowView rv = (DataRowView)r.Item; foreach (DataGridColumn column in DataGrid_Standard.Columns) { if (column.GetCellContent(r) is TextBlock) { TextBlock cellContent = column.GetCellContent(r) as TextBlock; MessageBox.Show(cellContent.Text); } else if (column.GetCellContent(r) is CheckBox) { CheckBox chk = column.GetCellContent(r) as CheckBox; MessageBox .Show (chk.IsChecked.ToString()); } } } public IEnumerable GetDataGridRows(Microsoft.Windows.Controls.DataGrid grid) { var itemsSource = grid.ItemsSource as IEnumerable; if (null == itemsSource) yield return null; foreach (var item in itemsSource) { var row = grid.ItemContainerGenerator.ContainerFromItem(item) as Microsoft.Windows.Controls.DataGridRow; if (null != row) yield return row; } }