windows-phone-7 - 当滚动查看器位于数据模板内时设置滚动查看器垂直偏移(wp7)

标签 windows-phone-7 datatemplate scrollviewer

我有一个数据透视表,其中每个数据透视表项都包含一个滚动查看器。 我想要做的是每次滚动到新的枢轴项目时将滚动查看器的偏移量设置为特定数字。我无法创建数据绑定(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/

相关文章:

c# - 如何覆盖 Windows Phone 8 中的 Windows 后退按钮?

wpf - 如何在 WPF 中编写数据模板/链接到子数据模板?

Silverlight ItemsControl 垂直滚动条,使用包装面板作为 ControlTemplate

wpf - 带有 DataTemplate 的 WPF 可编辑组合框的 SelectedItem 问题

c# - 在 2 个不同的滚动查看器中包含一个项目

WPF - ScrollView 困惑

windows-phone-7 - 图像动画 : Make Image move left and then back

c# - 如何滚动到 Windows Phone 7 列表框中的选定项目

windows-phone-7 - 测试 Windows Phone 7 中的连接问题(使用模拟器)

wpf - 在 tabControl 中为 TabItems 使用数据模板