检查 DataGrid 中的 Item 是否已经在视图中
Check if Item in a DataGrid is already in view
我有一个 DataGrid
,其中 ItemsSource
绑定到 ObservableCollection<LogEntry>
。单击 Button
后,用户可以滚动到特定的 LogEntry。因此我使用以下代码:
private void BringSelectedItemIntoView(LogEntry logEntry)
{
if (logEntry != null)
{
ContentDataGrid.ScrollIntoView(logEntry);
}
}
这很好用。但我不喜欢的是:如果 LogEntry 已经在视图中,那么 DataGrid
会很快闪烁。
我现在的问题是:
如果给定的 LogEntry 已经在视图中,是否有可能检查 DataGrid
?
您可以获得第一个可见项和最后一个可见项的索引
然后你可以检查你的项目的索引是否在 first 和 last 之内。
var verticalScrollBar = GetScrollbar(DataGrid1, Orientation.Vertical);
var count = DataGrid1.Items.Count;
var firstRow = verticalScrollBar.Value;
var lastRow = firstRow + count - verticalScrollBar.Maximum;
// check if item index is between first and last should work
获取滚动条方法
private static ScrollBar GetScrollbar(DependencyObject dep, Orientation orientation)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++)
{
var child = VisualTreeHelper.GetChild(dep, i);
var bar = child as ScrollBar;
if (bar != null && bar.Orientation == orientation)
return bar;
else
{
ScrollBar scrollBar = GetScrollbar(child, orientation);
if (scrollBar != null)
return scrollBar;
}
}
return null;
}
我有一个 DataGrid
,其中 ItemsSource
绑定到 ObservableCollection<LogEntry>
。单击 Button
后,用户可以滚动到特定的 LogEntry。因此我使用以下代码:
private void BringSelectedItemIntoView(LogEntry logEntry)
{
if (logEntry != null)
{
ContentDataGrid.ScrollIntoView(logEntry);
}
}
这很好用。但我不喜欢的是:如果 LogEntry 已经在视图中,那么 DataGrid
会很快闪烁。
我现在的问题是:
如果给定的 LogEntry 已经在视图中,是否有可能检查 DataGrid
?
您可以获得第一个可见项和最后一个可见项的索引
然后你可以检查你的项目的索引是否在 first 和 last 之内。
var verticalScrollBar = GetScrollbar(DataGrid1, Orientation.Vertical);
var count = DataGrid1.Items.Count;
var firstRow = verticalScrollBar.Value;
var lastRow = firstRow + count - verticalScrollBar.Maximum;
// check if item index is between first and last should work
获取滚动条方法
private static ScrollBar GetScrollbar(DependencyObject dep, Orientation orientation)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++)
{
var child = VisualTreeHelper.GetChild(dep, i);
var bar = child as ScrollBar;
if (bar != null && bar.Orientation == orientation)
return bar;
else
{
ScrollBar scrollBar = GetScrollbar(child, orientation);
if (scrollBar != null)
return scrollBar;
}
}
return null;
}