我有一个数据透视表,其中每个数据透视表项都包含一个滚动查看器。 我想要做的是每次滚动到新的枢轴项目时将滚动查看器的偏移量设置为特定数字。我无法创建数据绑定(bind),因为偏移值未公开。
我可以调用一个 ScrollToVerticalOffset() ,但我需要首先找到当前处于事件状态的滚动查看器并获取该对象,这意味着当前选定的枢轴项目内的滚动查看器。
我尝试通过根据名称遍历可视化树来获取滚动查看器,但我总是得到第一个滚动查看器。
我怎样才能做到这一点?
谢谢
最佳答案
您可以按类型而不是按名称遍历可视化树,并从选定的 PivotItem 开始,这意味着您找到的第一个 ScrollViewer 将是您想要的。
/// <summary>
/// Gets the visual children of type T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
/// <returns></returns>
public static IEnumerable<T> GetVisualChildren<T>(this DependencyObject target)
where T : DependencyObject
{
return GetVisualChildren(target).Where(child => child is T).Cast<T>();
}
/// <summary>
/// Get the visual tree children of an element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The visual tree children of an element.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="element"/> is null.
/// </exception>
public static IEnumerable<DependencyObject> GetVisualChildren(this DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return GetVisualChildrenAndSelfIterator(element).Skip(1);
}
/// <summary>
/// Get the visual tree children of an element and the element itself.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>
/// The visual tree children of an element and the element itself.
/// </returns>
private static IEnumerable<DependencyObject> GetVisualChildrenAndSelfIterator(this DependencyObject element)
{
Debug.Assert(element != null, "element should not be null!");
yield return element;
int count = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < count; i++)
{
yield return VisualTreeHelper.GetChild(element, i);
}
}
所以你最终会得到这样的结果:
var scroller = ((PivotItem)pivot.SelectedItem).GetVisualChildren().FirstOrDefault();
scroller.ScrollToVerticalOffset(offset);
关于windows-phone-7 - 当滚动查看器位于数据模板内时设置滚动查看器垂直偏移(wp7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747052/