你可以按類型而不是按名稱遍歷可視化樹,並在選定的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);
感謝名單德里克,它幫助 – johnX99 2011-01-21 15:46:26