How to autoscroll on WPF datagrid

后端 未结 17 1006
甜味超标
甜味超标 2020-12-08 09:27

I think I am stupid. I searched now for 15 minutes, and found several different solutions for scrolling on datagrids, but none seems to work for me.

I am using WPF w

17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 10:15

    I've found that the easiest way to do this is to call the ScrollIntoView method from the ScrollViewer.ScrollChanged attached event. This can be set in XAML as follows:

    
    

    The ScrollChangedEventArgs object has various properties that can be helpful for computing layout and scroll position (Extent, Offset, Viewport). Note that these are typically measured in numbers of rows/columns when using the default DataGrid virtualization settings.

    Here's an example implementation that keeps the bottom item in view as new items are added to the DataGrid, unless the user moves the scrollbar to view items higher up in the grid.

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

提交回复
热议问题