Programmatically scrolling WPF 4 DataGrid to end

旧街凉风 提交于 2019-12-30 11:12:20

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/14252408/programmatically-scrolling-wpf-4-datagrid-to-end

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!