【问题标题】:Get DataGrid row by index按索引获取 DataGrid 行
【发布时间】:2014-02-20 04:53:49
【问题描述】:

我正在尝试根据索引从我的DataGrid 获取DataGridRow。我正在使用以下代码:

public DataGridRow GetGridRow(int index)
{
    DataGridRow row = (DataGridRow)DG_Statement.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // May be virtualized, bring into view and try again.
        DG_Statement.UpdateLayout();
        DG_Statement.ScrollIntoView(DG_Statement.Items[index]);
        row = (DataGridRow)DG_Statement.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

参考链接 - Get row in datagrid

但不幸的是它返回了一个空对象DataGridRow。 如果我检查网格的 Items[] 属性,我可以看到 13 个项目。

需要有关如何获取网格行的建议,因为我想更改数据网格顶部 2 行和底部 2 行的颜色。

感谢任何帮助。谢谢!!

添加 DataGrid 项的屏幕截图

重要更新

如果我从 Grid 的 SelectedIndexChanged 事件中调用 GetGridRow(),它将完美运行。

另一方面,如果我在构建显示网格的页面对象之后调用它,它会将行对象返回为 NULL。

【问题讨论】:

  • 这个方法在哪里?代码在视图模型后面还是在视图模型中?
  • 这已经在堆栈溢出时被here 询问过。
  • 我在参考资料中提供了这个链接,并使用了该帖子中建议的代码。但是我得到了 Row 的空对象,这就是我被卡住的地方。
  • 听起来当时它还没有被初始化。
  • @MikeSchwartz:您能否建议任何解决方法来实现这一目标?

标签: c# .net wpf xaml


【解决方案1】:

所以如果它在后面的代码中。您可以只获取 DataGrid 的选定索引。我以datagrid dataGrid 为例。

var rowIndex = dataGrid.SelectedIndex;

var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex);

【讨论】:

  • 精心挑选的项目不会满足我的目的。我想更改网格的前 2 行和后 2 行的颜色。
【解决方案2】:

检查以确保您传入的索引实际上在范围内。

【讨论】:

  • 这正是我在上面发布的代码中所做的。我正在传递 index = 0。网格中的总项目数为 13,因此在范围内。此外,如果 row == null 则首先调用 UpdateLayout(),然后调用 ContainerFromIndex()。我使用 DataTable 视图作为我的 itemsource。会不会有什么问题?
  • 是的,我意识到你在我点击添加后再次调用它,所以我编辑它以尝试在有人注意到我的金发时刻之前删除该引用:)。
  • GetGridRow 调用发生在哪里?您可能在网格实际完成加载所有数据之前调用它。因为这发生在线程上,所以它可能会在调用之后填充,但在您检查 grid.Items 计数之前。
  • 添加了 DataGrid 项目计数的屏幕截图。
  • @NileshBarai 我在需要帮助时使用的示例位于stackoverflow.com/questions/5549617/…
猜你喜欢
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2015-09-24
相关资源
最近更新 更多