WPF数据网格 - 如何在添加新行时保持焦点在数据网格底部?

7
我正在使用DataGrid来自WPF Toolkit,我需要能够保持焦点在网格底部(即最后一行)。 我现在遇到的问题是,当添加行时,DataGrid的滚动条不会随着新行的添加而滚动。 最佳解决方法是什么?
3个回答

6

1
你在哪里调用这个方法? - joe
在你更新了数据源之后,只需要调用它即可。不过,在ScrollIntoView之前一定要调用UpdateLayout()! - Vinzz
2
为什么需要先调用UpdateLayout()?我以前不需要这样做。这只是某种最佳实践吗? - Taylor Leese

5

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

<DataGrid
...
ScrollViewer.ScrollChanged="control_ScrollChanged">
ScrollChangedEventArgs对象具有多个属性,可用于计算布局和滚动位置(Extent、Offset、Viewport)。请注意,在使用默认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]);
    }

5

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

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

请记得在网格加载完成后禁用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接