我想访问DataGrid.I中的元素,我正在使用下面的code.But,我无法得到DataGrid该行,我得到的是null值,我只想知道为什么我获得null值,以及如何解决这个问题。
int itemscount = (dgMtHdr.Items.Count);
dgMtHdr.UpdateLayout();
for (int rowidx = 0; rowidx < itemscount; rowidx++)
{
Microsoft.Windows.Controls.DataGridRow dgrow = (Microsoft.Windows.Controls.DataGridRow)this.dgMtHdr.ItemContainerGenerator.ContainerFromIndex(rowidx);
if (dgrow != null)
{
DataRow dr = ((DataRowView)dgrow.Item).Row;
if (dr != null)
{
obj = new WPFDataGrid();
Microsoft.Windows.Controls.DataGridCell cells = obj.GetCell(dgMtHdr, rowidx, 7);
if (cells != null)
{
ContentPresenter panel = cells.Content as ContentPresenter;
if (panel != null)
{
ComboBox cmb = obj.GetVisualChild<ComboBox>(panel);
}
}
}
}
}发布于 2013-04-14 17:11:08
DataGrid内部托管来自VirtualizingStackPanel的DataGridRowsPresenter中的项,这意味着默认情况下在UI上呈现的项支持虚拟化,即不会为尚未在UI上呈现的项生成ItemContainer。
这就是为什么在尝试获取未在UI上呈现的行时获得null的原因。
所以,如果你准备好和虚拟化做交易,你可以像这样turn off the Virtualization -
<DataGrid x:Name="dgMtHdr" VirtualizingStackPanel.IsVirtualizing="False"/>现在,对于任何索引值,DataGridRow都不会为空。
或
您可以通过为索引手动调用UpdateLayout()和ScrollIntoView()来获得行,以便为您生成容器。有关详细信息,请参阅此链接here。从链接中-
if (row == null)
{
// May be virtualized, bring into view and try again.
grid.UpdateLayout();
grid.ScrollIntoView(grid.Items[index]);
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
}编辑
因为您的DataGrid位于第二个选项卡中,因此尚未呈现。这就是为什么它的ItemContainerGenerator没有生成项目所需的相应容器的原因。所以,一旦通过链接到StausChanged事件生成了条目容器,您就需要这样做-
dgMtHdr.ItemContainerGenerator.StatusChanged += new
EventHandler(ItemContainerGenerator_StatusChanged);
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if ((sender as ItemContainerGenerator).Status ==
GeneratorStatus.ContainersGenerated)
{
// ---- Do your work here and you will get rows as you intended ----
// Make sure to unhook event here, otherwise it will be called
// unnecessarily on every status changed and moreover its good
// practise to unhook events if not in use to avoid any memory
// leak issue in future.
dgMtHdr.ItemContainerGenerator.StatusChanged -=
ItemContainerGenerator_StatusChanged;
}
}https://stackoverflow.com/questions/16001306
复制相似问题