Dan*_*ett 3 .net c# wpf datagrid off-by-one
我有一个DataGrid可变维度依赖于screen-res.我需要知道用户可以看到多少行.这是我的代码:
uint VisibleRows = 0;
var TicketGrid = (DataGrid) MyWindow.FindName("TicketGrid");
foreach(var Item in TicketGrid.Items) {
var Row = (DataGridRow) TicketGrid.ItemContainerGenerator.ContainerFromItem(Item);
if(Row != null && Row.IsVisible) {
VisibleRows++;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用以下代码来测试变量:
MessageBox.Show(String.Format("{0} of {1} rows visible", VisibleRows, TicketGrid.Items.Count));
Run Code Online (Sandbox Code Playgroud)






我不能只是- 1,因为在添加了一定数量之后它才是不正确的.我无法检查> 10,因为尺寸是可变的.
我怎样才能解决这个问题?
这是最终对我有用的东西:
uint VisibleRows = 0;
var TicketGrid = (DataGrid) MyWindow.FindName("TicketGrid");
foreach(var Item in TicketGrid.Items) {
var Row = (DataGridRow) TicketGrid.ItemContainerGenerator.ContainerFromItem(Item);
if(Row != null) {
/*
This is the magic line! We measure the Y position of the Row, relative to
the TicketGrid, adding the Row's height. If it exceeds the height of the
TicketGrid, it ain't visible!
*/
if(Row.TransformToVisual(TicketGrid).Transform(new Point(0, 0)).Y + Row.ActualHeight >= TicketGrid.ActualHeight) {
break;
}
VisibleRows++;
}
}
Run Code Online (Sandbox Code Playgroud)
最高并包括第9行显示9中的9个可见."半可见"行10导致10个中的9个可见.实际上,对于我的目的来说,这不是一个可见的行,所以这对我来说真的更好!:)
注意:如果您在不使用的情况下重复使用我的代码break,那么在违规行之后的任何不可见行都会抛出NullRefException.