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

前端 未结 9 1100
旧巷少年郎
旧巷少年郎 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:56

    As Dr.WPF has answered a similar question here the RequestBringIntoView should be handled in ItemsPanel.

    0 讨论(0)
  • 2020-12-08 07:57

    Define an EventSetter in the DataGrid.RowStyle to call a handler that prevents the row from being brought into view:

    XAML

    <DataGrid>
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">  
                <EventSetter Event="Control.RequestBringIntoView" Handler="DataGrid_Documents_RequestBringIntoView"  />
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
    

    Handler

    private void DataGrid_Documents_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
    {
        e.Handled = true;      
    }
    
    0 讨论(0)
  • 2020-12-08 08:01

    I'm not sure this is working but here is an idea based on some investigation is made in the DataGrid's source code using Reflector:

    1/ create a class which inherits DataGridCellsPanel. This is the Panel that is used internally by the DataGrid in order to arrange the cells

    2/ override the BringIndexIntoView method by an empty method (without calling the base method)

    3/ set the ItemsPanelTemplate property in your XAML:

    <tk:DataGrid>
        <tk:DataGrid.ItemsPanel>
            <ItemsPanelTemplate>
                <local:DataGridCellsPanelNoAutoScroll />
            </ItemsPanelTemplate>
        </tk:DataGrid.ItemsPanel>
    </tk:DataGrid>
    

    It seems that when a MouseDown event occurs, at some point the BringIndexIntoView method of the panel is called to do the auto-scroll. Replacing it with a no-op might do the trick.

    I hadn't time to test this solution, please let us know if it's working.

    0 讨论(0)
提交回复
热议问题