WPF DataGrid - How to focus on the bottom of the DataGrid when adding new rows?

I am using the DataGrid from the WPF Toolkit , and I need to be able to focus on the bottom of the grid (i.e. on the last row). The problem I am facing now is that as you add rows, the scroll bar for the DataGrid does not scroll along with the addition of new rows. What is the best way to accomplish this?

+7
c # wpf datagrid focus
source share
3 answers

It looks like DataGrid.ScrollIntoView(<item>) will keep focus at the bottom of the DataGrid .

+6
source share

I found that the most useful time to call the ScrollIntoView method is the event associated with ScrollViewer.ScrollChanged. This can be installed in XAML as follows:

 <DataGrid ... ScrollViewer.ScrollChanged="control_ScrollChanged"> 

The ScrollChangedEventArgs object has various properties that can be useful for calculating the layout and scroll position (Extent, Offset, Viewport). Note that they are usually measured in row / column counts using the default virtualization settings of the DataGrid.

Here is an example implementation that saves the bottom item in the view, as new items are added to the DataGrid if the user does not move the scroll bar to view items higher 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]); } 
+5
source share

This is a simple approach using the LoadRow event:

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

Just remember to turn it off after loading the grid.

+4
source share

All Articles