以编程方式滚动WPF 4 DataGrid以结束 [英] Programmatically scrolling WPF 4 DataGrid to end
问题描述
有人知道通过编程将WPF DataGrid(.NET 4)滚动到最后一行的可靠方法吗?
Does anyone know of a reliable approach for scrolling a WPF DataGrid (.NET 4) to the last row programmatically?
m知道 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?
PS使用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以结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!