wpf datagrid Ienumerable returning null

本文关键字:null returning Ienumerable datagrid wpf | 更新日期: 2023-09-27 18:07:18

使用c# . net 4.5, MS Visual Studio 2012, WPF。

嗨,伙计们,这里有一些代码给我null。这段代码是我之前尝试过的解决方案。我没有收到任何错误,但从来没有测试过,因为今天当我发现我调试有行是空的。

下面是代码:

首先我把我的数据从SQL收集到一个数据表,并把它扔到我的数据网格…

 private void LoadPareto(string pg)
 {
     DataTable tbl = new DataTable();
     tbl = mysqlq.SQL_GetPareto(pg);
     paretogrid.ItemsSource = tbl.AsDataView();
     // InsertColumns();
     ShowArrows();
 }
<DataGrid Name ="paretogrid" ItemsSource="{Binding}"

我创建了一个Ienumerable…

public IEnumerable<System.Windows.Controls.DataGridRow> GetDataGridRow(System.Windows.Controls.DataGrid grid)
{
    var itemsource = grid.ItemsSource as System.Collections.IEnumerable;
    if (null == itemsource) yield return null;
    foreach (var item in itemsource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow; // null?
        if (null != row) yield return row;
    }
}

然后在这个方法中调用它…

private void ShowArrows()
{
    var rows = GetDataGridRow(paretogrid); // fetching null?
    foreach (DataGridRow r in rows)
    {
        DataRowView rv = (DataRowView)r.Item;
        foreach (DataGridColumn column in paretogrid.Columns)
        {
            if (column.GetCellContent(r) is TextBlock)
            {
                TextBlock cellcontent = column.GetCellContent(r) as TextBlock;
                MessageBox.Show(cellcontent.Text);
            }
        }
    }
}

现在我的问题是在Ienumerbale中,我看到我的项目源包含12007条记录,这是完美的。然而,当我走过的时候,我发现……

var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;

返回null,我的"if"语句发现它为false,因此跳过yield。所以,当然,当我在" showrows "方法中执行foreach循环时,它不会因为有null而烦恼。

我哪里错了?我错过什么了吗?

提前感谢男孩和女孩!

wpf datagrid Ienumerable returning null

当您获得行时,您的DataGrid尚未更新。解决方案是在设置ItemsSource后立即设置paretogrid.UpdateLayout()

注意,混合数据和UI代码并不是很好。您尝试做的事情可能已经在XAML中完成,并且您不会有这个问题。