wpf 按索引获取 DataGrid 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21413259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:38:25  来源:igfitidea点击:

Get DataGrid row by index

c#.netwpfxaml

提问by Nilesh Barai

I am trying to obtain DataGridRowfrom my DataGridbased on index. I am using following code:

我试图DataGridRow从我的DataGrid基于索引中获取。我正在使用以下代码:

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;
}

Ref Link - Get row in datagrid

参考链接 -获取数据网格中的行

But unfortunately its returning a null object of DataGridRow. If I check the Items[]property of my grid I could see 13 items.

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

Need suggestion on how to obtain the Grid Row as I want to change color of top 2 and bottom 2 rows of my data grid.

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

Any help is appreciated. Thanks!!

任何帮助表示赞赏。谢谢!!

Adding Screenshot of DataGrid Items

添加 DataGrid 项目的屏幕截图

enter image description here

在此处输入图片说明

Important Update

重要更新

If I call GetGridRow() from the SelectedIndexChanged Event of the Grid it works flawlessly.

如果我从网格的 SelectedIndexChanged 事件中调用 GetGridRow(),它可以完美地工作。

On the other hand, if I call it after I construct the object of the page on which my grid is displayed it returns row object as NULL.

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

回答by Mike Schwartz

So if its in the code behind. You can just get the selected index of the DataGrid. I've named the datagrid dataGrid as an example.

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

var rowIndex = dataGrid.SelectedIndex;

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

回答by Leeland Clay

Check to make sure the index you're passing in is actually within bounds.

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