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

Tay*_*ese 7 .net c# wpf datagrid focus

我使用DataGridWPF工具包,我需要能够保持专注于网格的底部(即最后一排).我现在遇到的问题是,当添加行时,滚动条DataGrid不会随着要添加的新行一起滚动.实现这一目标的最佳方法是什么?

Tay*_*ese 6

看起来DataGrid.ScrollIntoView(<item>)会将焦点放在底部DataGrid.

  • 为什么需要先调用UpdateLayout()?我不必那样做.这只是出于某种原因的最佳做法吗? (2认同)

bab*_*ari 5

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

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

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


Mat*_*att 5

我发现调用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)