获取数据网格的滚动查看器 [英] Get datagrid's scrollviewer
问题描述
我正在尝试让数据网格的滚动查看器能够设置偏移量(之前已存储).
I'm trying to get the datagrid's scrollviewer to be able to set the offset (which has been stored earlier).
我使用这个功能:
public static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
我这样称呼它:
this.dataGrid.ItemsSource = _myData;
ScrollViewer sc = ressource_design.GetVisualChild<ScrollViewer>(this.dataGrid);
if (sc != null) sc.ScrollToVerticalOffset(stateDatagrid.ScrollbarOffset);
它在许多情况下都有效,但在某些情况下,该函数返回 null,我无法获得滚动查看器.
And it works in many cases, but in some cases the function returns null and I'm not able to get the scrollviewer.
这个调用是在设置 ItemsSource (ObservableCollection of items) 之后进行的,它在 90% 的情况下运行良好.数据网格尚未呈现.
This call is made just after setting the ItemsSource (ObservableCollection of items) and it works well in 90% cases. The datagrid has not been rendered yet.
我也试过这个功能:
public static ScrollViewer GetScrollViewerFromDataGrid(DataGrid dataGrid)
{
ScrollViewer retour = null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dataGrid) && retour == null; i++)
{
if (VisualTreeHelper.GetChild(dataGrid, i) is ScrollViewer)
{
retour = (ScrollViewer)(VisualTreeHelper.GetChild(dataGrid, i));
}
}
return retour;
}
仍然为空.
为什么我无法获得数据网格的滚动查看器?
Why I'm unable to get the datagrid's scrollviewer ?
我没有粘贴我的数据网格的样式,因为我有数据网格使用它并且它具有许多依赖项而很复杂.
I've not pasted my datagrid's style since I have datagrids working with it and it is complicated with many dependencies.
我认为这可能与虚拟化有关,但我无法检索此数据网格的滚动查看器:
I thought it could be related to virtualization but i'm not able to retrieve the scrollviewer of this datagrid :
<DataGrid Style="{StaticResource StyleDataGrid}" HeadersVisibility="None" ItemsSource="{Binding _Data}" Name="dataGrid1" RowDetailsVisibilityMode="Visible" SelectionChanged="dataGrid1_SelectionChanged">
推荐答案
您需要递归遍历 VisualTree
元素.您的函数只查看 DataGrid
层.如果 ScrollViewer
不存在(见图片),您将找不到它.
You need to go recursive through the VisualTree
elements. Your function only looks at DataGrid
layer. If the ScrollViewer
isn't there (see picture) you will not find it.
试试下面的函数:
public static ScrollViewer GetScrollViewer(UIElement element)
{
if (element == null) return null;
ScrollViewer retour = null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element) && retour == null; i++) {
if (VisualTreeHelper.GetChild(element, i) is ScrollViewer) {
retour = (ScrollViewer) (VisualTreeHelper.GetChild(element, i));
}
else {
retour = GetScrollViewer(VisualTreeHelper.GetChild(element, i) as UIElement);
}
}
return retour;
}
这篇关于获取数据网格的滚动查看器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!