Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically scrolling WPF 4 DataGrid to end

Tags:

wpfdatagrid

Does anyone know of a reliable approach for scrolling a WPF DataGrid (.NET 4) to the last row programmatically?

I'm aware of ScrollIntoView(Items[Items.Count-1]), but this works only if the items are unique.

For instance, consider the following DataGrid which displays all the installed cultures, followed by all the installed cultures:

var cultures = System.Globalization.CultureInfo.GetCultures (System.Globalization.CultureTypes.AllCultures);
var timesTwo = cultures.Concat (cultures).ToArray();

var grid = new DataGrid { ItemsSource = timesTwo };

How can this grid be programmatically scrolled to the last row?

P.S. Another problem with using ScrollIntoView is that if the grid is itself in a scrollable container (e.g., inside another grid), then ScrollIntoView scrolls not only its own grid, but the outer grid as well such that requested element is visible on the screen. This might be beneficial in some cases, but certainly not in others.

like image 558
Joe Albahari Avatar asked Apr 20 '26 11:04

Joe Albahari


1 Answers

For anyone with this problem, the following seems to do the trick:

var scrollerViewer = GetScrollViewer();
if (scrollerViewer != null) scrollerViewer.ScrollToEnd();

...

ScrollViewer GetScrollViewer()
{
   if (VisualTreeHelper.GetChildrenCount (this) == 0) return null;
   var x = VisualTreeHelper.GetChild (this, 0);
   if (x == null) return null;
   if (VisualTreeHelper.GetChildrenCount (x) == 0) return null;
   return VisualTreeHelper.GetChild (x, 0) as ScrollViewer;
}
like image 77
Joe Albahari Avatar answered Apr 24 '26 00:04

Joe Albahari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!