Search code examples
wpfdatagridrow

How to scroll to a given row when WPF DataGrid is loaded


I display a few thousand rows in a WPF DataGrid, but would like to automatically scroll to a specific row when it is loaded (and later also add a button to scroll to this specific row). Is it possible to achieve it via data binding or from a view model property?

Of course, I've already browsed the Internet, but could not find any corresponding property.. For exemple, SelectedCells only has a get accessor (but I don't think it would have scrolled whatsoever anyway). I don't think that the other properties, such as SelectedItem helps.

Thanks for any insights :-)


Solution

  • There are two options: scroll to a row without selecting it and scroll to a row and select it.

    Scroll to row without selecting it

    This solution works for any DataGrid.SelectionUnit value (cell or row based selection).

    You set the row from a property in your view model, which binds to DataGrid.CurrentItem.

    Scrolling must be handled by the DataGrid by handling the DataGrid.CurrentCellChanged event.

    View model (must implement INotifyPropertyChanged)

    object currentRow = this.DataSource[currentRowIndex];
    this.CurrentRow = currentRow;
    

    View.xaml

    <DataGrid ItemsSource="{Binding DataSource}"  
              CurrentItem="{Binding CurrentRow}"
              CurrentCellChanged="DataGrid_OnCurrentCellChanged" />
    

    View.xaml.cs

    private void DataGrid_OnCurrentCellChanged(object sender, EventArgs eventArgs)
    {
      var dataGrid = sender as DataGrid;
      dataGrid.ScrollIntoView(dataGrid.CurrentItem);
    }
    

    Scroll to row by selecting it

    This solution works only for DataGrid.SelectionUnit values DataGridSelectionUnit.FullRow or DataGridSelectionUnit.CellOrRowHeader (not cell-only based selection - cell-only solution must completely handle selection and scroll in view).

    You set the selected row from a property in your view model, which binds to DataGrid.SelectedItem.

    Scrolling must be handled by the DataGrid by handling the DataGrid.SelectionChanged event.

    View model (must implement INotifyPropertyChanged)

    object selectedRow = this.DataSource[currentRowIndex];
    this.SelectedRow = selectedRow;
    

    View.xaml

    <DataGrid ItemsSource="{Binding DataSource}"  
              SelecetedItem="{Binding SelectedRow}"
              SelectionChanged="DataGrid_OnCurrentCellChanged" />
    

    View.xaml.cs

    private void DataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs eventArgs)
    {
      var dataGrid = sender as DataGrid;
      dataGrid.ScrollIntoView(dataGrid.SelectedItem);
    }