I have a pivot where each pivotItem contains a scrollviewer. What I want to do is to set 开发者_开发知识库the scrollviewer's offset to a specific number each time I scroll to a new pivot item. I cannot create a databinding because the offset value is not exposed.
There is a ScrollToVerticalOffset() that i can call, but I need first to find which scrollviewer is currently active and get that object, which means the scrollviewer inside the currently selected pivot item.
I tried to get the scrollviewer by traversing the visual tree based on its name but I always get the 1st scrollviewer.
How could I do that?
thanx
You could traverse the visual tree by type instead of by name and start at the selected PivotItem, which should mean that the first ScrollViewer that you find will be the one you want.
/// <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);
}
}
So you'd end up with something like this:
var scroller = ((PivotItem)pivot.SelectedItem).GetVisualChildren().FirstOrDefault();
scroller.ScrollToVerticalOffset(offset);
精彩评论