问题描述
有谁知道以编程方式将 WPF DataGrid (.NET 4) 滚动到最后一行的可靠方法?
Does anyone know of a reliable approach for scrolling a WPF DataGrid (.NET 4) to the last row programmatically?
我知道 ScrollIntoView(Items[Items.Count-1])
,但这仅在项目唯一时才有效.
I'm aware of ScrollIntoView(Items[Items.Count-1])
, but this works only if the items are unique.
例如,考虑以下 DataGrid,它显示所有已安装的文化,然后是所有已安装的文化:
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?
附言使用 ScrollIntoView 的另一个问题是,如果网格本身在可滚动容器中(例如,在另一个网格内),那么 ScrollIntoView 不仅滚动它自己的网格,而且滚动外部网格,这样请求的元素在屏幕上可见.这在某些情况下可能是有益的,但在其他情况下肯定不是.
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.
推荐答案
对于遇到此问题的任何人,以下似乎可以解决问题:
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;
}
这篇关于以编程方式滚动 WPF 4 DataGrid 以结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!