为什么ItemContainerGenerator.ContainerFromIndex()返回null并且如何避免这种行为? [英] Why ItemContainerGenerator.ContainerFromIndex() returns null and how to avoid this behavior?

查看:1416
本文介绍了为什么ItemContainerGenerator.ContainerFromIndex()返回null并且如何避免这种行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码片段分析我在datagrid上选择的行。

I'm using this snippet to analyze the rows I've selected on a datagrid.

for (int i = 0; i < dgDetalle.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dgDetalle.ItemContainerGenerator.ContainerFromIndex(i);
    FrameworkElement cellContent = dgDetalle.Columns[0].GetCellContent(row);
    // ... code ...
}

循环运行顺利地,但是当处理某些索引时,第二行将抛出一个空异常。 MSDN的文档说,如果项目没有实现, ItemContainerGenerator.ContainerFromIndex(i)将返回null,但这并不能帮助我猜测如何获得所需的值。

The cycle runs smoothly, but when processing certain indexes, the second line throws a null exception. MSDN's documentation says that ItemContainerGenerator.ContainerFromIndex(i) will return null if 'if the item is not realized', but this doesn't help me to guess how could I get the desired value.

如何扫描所有行?有没有其他方法?

How can I scan all the rows? Is there any other way?

更新

我正在使用这个代码段如此处所述,阅读 CheckBox 。所以我不能使用绑定或 ItemSource ,除非我改变了很多事情。我不能。我在做代码维护

I'm using this snippet to read a CheckBox as explained here. So I can't use binding or ItemSource at all unless I change a lot of things. And I cannot. I'm doing code maintenance.

推荐答案

DataGrid 正在虚拟化项目,相应的行容器)仅在行被查看时才创建。

The DataGrid is virtualizing the items, the respective rows (i.e. containers) are only created when the row is in view.

您可以关闭虚拟化(这使得第一次加载非常慢,如果你有很多项目,内存使用率也会更高)或您只需迭代数据并检查应绑定到数据网格的数据对象属性的值。通常你根本不需要UI元素...

You could either turn off virtualization (which makes the first time loading very slow if you have many items, also the memory usage will be higher) or you just iterate over the data and check the values of the data objects' properties which should be bound to the data-grid. Usually you should not need the UI elements at all...

这篇关于为什么ItemContainerGenerator.ContainerFromIndex()返回null并且如何避免这种行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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