C# WPF DataGrid-当添加新行时,如何保持对DataGrid底部的关注?

C# WPF DataGrid-当添加新行时,如何保持对DataGrid底部的关注?,c#,.net,wpf,datagrid,focus,C#,.net,Wpf,Datagrid,Focus,我从使用,我需要能够保持对网格底部(即最后一行)的关注。我现在遇到的问题是,随着行的添加,DataGrid的滚动条不会随着新行的添加而滚动。实现这一点的最佳方法是什么?看起来将重点放在数据网格的底部这是一种使用LoadingRow事件的简单方法: void dataGrid_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e) { dataGrid.ScrollIntoView(e.Row.It

我从使用,我需要能够保持对网格底部(即最后一行)的关注。我现在遇到的问题是,随着行的添加,
DataGrid
的滚动条不会随着新行的添加而滚动。实现这一点的最佳方法是什么?

看起来将重点放在
数据网格的底部

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

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

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

我发现调用该方法最有用的时间是从ScrollViewer.ScrollChanged attached事件。这可以在XAML中设置,如下所示:

<DataGrid
...
ScrollViewer.ScrollChanged="control_ScrollChanged">

对象具有各种属性,这些属性有助于计算布局和滚动位置(范围、偏移、视口)。请注意,在使用默认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]);
    }
private void control\u ScrollChanged(对象发送方,ScrollChangedEventArgs e)
{
//如果整个内容都显示在屏幕上,则忽略此事件
if(e.延伸灯if(this.Items.Count)您在哪里调用此方法?确实如此。在使用新元素更新数据源后进行调用。但是,请确保在ScrollIntoView之前调用UpdateLayout()!为什么需要先调用UpdateLayout()?我不必这样做。出于某种原因,这只是一种最佳做法吗?