我正在使用
DataGrid
来自WPF Toolkit,我需要能够保持焦点在网格底部(即最后一行)。 我现在遇到的问题是,当添加行时,DataGrid
的滚动条不会随着新行的添加而滚动。 最佳解决方法是什么?DataGrid.ScrollIntoView(<item>)
可以让 DataGrid
保持焦点在底部。我发现调用ScrollIntoView方法最有用的时机是从ScrollViewer.ScrollChanged附加事件中。可以在XAML中设置如下:
<DataGrid
...
ScrollViewer.ScrollChanged="control_ScrollChanged">
ScrollChangedEventArgs对象具有多个属性,可用于计算布局和滚动位置(Extent、Offset、Viewport)。请注意,在使用默认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);
}
请记得在网格加载完成后禁用它。