WPF DataGrid – 如何在添加新行时将注意力集中在DataGrid的底部?

我正在使用WPF工具包中的 DataGrid ,我需要能够将焦点保持在网格的底部(即最后一行)。 我现在遇到的问题是,在添加行时, DataGrid的滚动条不会随着要添加的新行一起滚动。 实现这一目标的最佳方法是什么?

看起来像DataGrid.ScrollIntoView()将焦点保持在DataGrid的底部。

我发现调用ScrollIntoView方法最有用的时间来自ScrollViewer.ScrollChanged附加事件。 这可以在XAML中设置如下:

  

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]); } 

这是使用LoadingRow事件的简单方法:

 void dataGrid_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e) { dataGrid.ScrollIntoView(e.Row.Item); } 

只需记住在网格加载完成后禁用它。