【问题标题】:Setting the scrollviewer vertical offset when the scrollviewer is inside a datatemplate (wp7)当滚动查看器位于数据模板内时设置滚动查看器垂直偏移量(wp7)
【发布时间】:2011-01-21 00:55:12
【问题描述】:

我有一个枢轴,其中每个枢轴项都包含一个滚动查看器。 我想要做的是每次滚动到新的数据透视项时将滚动查看器的偏移量设置为特定数字。我无法创建数据绑定,因为未公开偏移值。

我可以调用一个 ScrollToVerticalOffset(),但我首先需要找到当前处于活动状态的滚动查看器并获取该对象,这意味着当前选定的枢轴项目内的滚动查看器。

我试图通过根据名称遍历可视化树来获取滚动查看器,但我总是得到第一个滚动查看器。

我该怎么做?

感谢

【问题讨论】:

    标签: windows-phone-7 datatemplate scrollviewer


    【解决方案1】:

    您可以按类型而不是名称遍历可视化树并从选定的 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2018-08-06
      • 2012-03-16
      相关资源
      最近更新 更多