按索引获取DataGrid行 [英] Get DataGrid row by index

查看:35
本文介绍了按索引获取DataGrid行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to obtain DataGridRow from my DataGrid based on index. I am using following code:

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

引用链接-在datagrid中获取行

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

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

当我想更改数据网格的前2行和后2行的颜色时,需要有关如何获取网格行"的建议.

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.

感谢您的帮助.谢谢!

添加DataGrid项目的屏幕截图

Adding Screenshot of DataGrid Items

重要更新

如果我从Grid的SelectedIndexChanged事件中调用GetGridRow(),它将正常工作.

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

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

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.

推荐答案

因此,如果它在代码后面.您可以仅获取DataGrid的选定索引.我以datagrid dataGrid为例.

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.

var rowIndex = dataGrid.SelectedIndex;

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

这篇关于按索引获取DataGrid行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆