I have a DataGrid where the ItemsSource is bound to an ObservableCollection<LogEntry>. On a click on a Button the user can scroll to a specific LogEntry. Therefor I use the following code:
private void BringSelectedItemIntoView(LogEntry logEntry)
{
if (logEntry != null)
{
ContentDataGrid.ScrollIntoView(logEntry);
}
}
Run Code Online (Sandbox Code Playgroud)
This just works fine. But what I don't like is: If the LogEntry already is in view then the DataGrid flickers shortly.
My question now is:
是否有可能检查DataGrid给定的 LogEntry 是否已经在视图中?
您可以获得第一个可见项目和最后一个可见项目的索引
然后你可以检查你的项目的索引是否在第一个和最后一个范围内。
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
Run Code Online (Sandbox Code Playgroud)
获取滚动条方法
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
905 次 |
| 最近记录: |