WPF DataGrid: how do I stop auto scrolling when a cell is clicked?

前端 未结 9 1124
旧巷少年郎
旧巷少年郎 2020-12-08 07:31

Problem:
If my DataGrid is not entirely visible (horizontal & vertical scrollbars are showing) and I click on one of my cells that is p

9条回答
  •  执念已碎
    2020-12-08 07:54

    I had the same problem and Jan's answer helped me. The only missing thing was that ScrollContentPresenter will be found only after Loaded event occurs. I created an extended DataGrid class inherited from DataGrid with additional property AutoScroll to control if I want the grid to scroll automatically or not.

    Here's the class:

    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Windows.Controls;
    
    namespace Bartosz.Wojtowicz.Wpf
    {
        public class ExtendedDataGrid : DataGrid
        {
            public bool AutoScroll { get; set; }
    
            public ExtendedDataGrid()
            {
                AutoScroll = true;
                Loaded += OnLoaded;
            }
    
            private void OnLoaded(object sender, RoutedEventArgs eventArgs)
            {
                if (!AutoScroll)
                {
                    ScrollContentPresenter scp = DataGridHelper.GetVisualChild(this);
                    if (scp != null) scp.RequestBringIntoView += OnRequestBringIntoView;
                }
            }
    
            private static void OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
            {
                e.Handled = true;
            }
        }
    }
    

    And here's how you use it:

       
            
       
    

提交回复
热议问题