WPF迭代数据网格

lem*_*unk 14 c# wpf datagrid

使用Visual Studio 2012 ulti使用WPF C#.NET4.5.

旧winforms代码:

foreach (DataGridViewRow paretoRow in ParetoGrid.Rows)
{
       if ((Convert.ToInt32(paretoRow.Cells["CurrentPareto"].Value) < (Convert.ToInt32(paretoRow.Cells["NewPareto"].Value))))
       {
              paretoRow.Cells["pNew"].Value = downArrow
       }
}
Run Code Online (Sandbox Code Playgroud)

你可以看到我循环的每一行我检查一个特定的单元格,如果是,我然后填充另一个单元格.这是我以前用过很多次的好的winforms代码......但是.切换到WPF与我之前假设的有很多不同.

DataGrid不包含该Row属性.相反,我认为你需要使用:

DataGridRow paretoRow in paretogrid.Items
Run Code Online (Sandbox Code Playgroud)

但我现在仍然不知道谁将获得这个细胞.

所以我的问题是,是否有语法更改要执行,如果是这样的话?或者我开始相信WPF中的数据网格比使用对象操作更多,因此不需要使用称为"行"的属性,如果是这种情况,我应该知道在这个例子中应该使用什么逻辑/语法?

感谢您的耐心等待,想想当我回家度假时,我会做一些WPF挖掘,看看它实际上有多么不同.

COL*_*OLD 23

我想首先想你要做的就是得到你的所有行DataGrid:

public IEnumerable<Microsoft.Windows.Controls.DataGridRow> 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后遍历你的网格:

var rows = GetDataGridRows(nameofyordatagrid); 

foreach (DataGridRow row in rows)  
{  
  DataRowView rowView = (DataRowView)row.Item;
  foreach (DataGridColumn column in nameofyordatagrid.Columns)
  {
      if (column.GetCellContent(row) is TextBlock)
      {
          TextBlock cellContent = column.GetCellContent(row) as TextBlock;
          MessageBox.Show(cellContent.Text);
      }
  } 
Run Code Online (Sandbox Code Playgroud)


Cha*_*ton 22

人们似乎过于复杂,这对我有用:

foreach (System.Data.DataRowView dr in yourDataGrid.ItemsSource)
{
     MessageBox.Show(dr[0].ToString());
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为人们喜欢让事情变得比他们必须的更复杂。 (2认同)