看起来DataGrid.ScrollIntoView(<item>)
会将焦点放在底部DataGrid
.
这是一个使用LoadingRow事件的简单方法:
void dataGrid_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
{
dataGrid.ScrollIntoView(e.Row.Item);
}
Run Code Online (Sandbox Code Playgroud)
只需记住在网格加载完成后禁用它.
我发现调用ScrollIntoView方法最有用的时间来自ScrollViewer.ScrollChanged附加事件.这可以在XAML中设置如下:
<DataGrid
...
ScrollViewer.ScrollChanged="control_ScrollChanged">
Run Code Online (Sandbox Code Playgroud)
所述ScrollChangedEventArgs对象具有各种性质,可以是用于计算布局有益的和滚动位置(程度上抵消,视口).请注意,这些通常使用默认的DataGrid虚拟化设置以行/列数量来衡量.
这是一个示例实现,它将新项目添加到DataGrid时将底部项目保持在视图中,除非用户移动滚动条以查看网格中较高的项目.
private void control_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
// If the entire contents fit on the screen, ignore this event
if (e.ExtentHeight < e.ViewportHeight)
return;
// If no items are available to display, ignore this event
if (this.Items.Count <= 0)
return;
// If the ExtentHeight and ViewportHeight haven't changed, ignore this event
if (e.ExtentHeightChange == 0.0 && e.ViewportHeightChange == 0.0)
return;
// If we were close to the bottom when a new item appeared,
// scroll the new item into view. We pick a threshold of 5
// items since issues were seen when resizing the window with
// smaller threshold values.
var oldExtentHeight = e.ExtentHeight - e.ExtentHeightChange;
var oldVerticalOffset = e.VerticalOffset - e.VerticalChange;
var oldViewportHeight = e.ViewportHeight - e.ViewportHeightChange;
if (oldVerticalOffset + oldViewportHeight + 5 >= oldExtentHeight)
this.ScrollIntoView(this.Items[this.Items.Count - 1]);
}
Run Code Online (Sandbox Code Playgroud)