本文介绍了如何检查 UI 元素是否已到达 Windows Phone 中的页面顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个页面,它有一个滚动查看器和一些本质上是动态的内容.在页面中间有一个网格.每当用户滚动页面和网格到达页面顶部时,我想要一个通知程序.基本上我想让网格在到达页面顶部时粘在顶部.有什么方法可以在 Windows 手机应用程序中实现这一点.我不想计算偏移量,因为页面顶部和网格之间的内容是动态的.

There is a page which has a scroll viewer and some content which is dynamic in nature. In the middle of the page there is a grid. Whenever the user scrolls the page and grid reaches the top of the page i want a notifier. Basically i want to make the grid sticky on top whenever it reaches top of the page. Is there any way we can achieve this in Windows phone application. I dont want to calculate the offset because the content between top of the page and grid is dynamic.

推荐答案

这曾经很棘手,但多亏了新的 Windows Composition API,现在相当简单.

This used to be tricky to do but thanks to the new Windows Composition API, it's now fairly simple.

假设我有一个名为 MainScrollScrollViewer,它承载了一个名为 StickyGridGrid,我想制作后者粘性一旦到达顶部.

Let's say I have a ScrollViewer named MainScroll which hosts a Grid called StickyGrid and I want to make the latter sticky once it hits the top.

代码带有注释来解释它的作用.

There's the code with comments to explain what it does.

MainScroll.SizeChanged += (s, e) =>
{
    // Let's first get the offset Y for the main ScrollViewer relatively to the sticky Grid.
    var transform = ((UIElement)MainScroll.Content).TransformToVisual(StickyGrid);
    var offsetY = (float)transform.TransformPoint(new Point(0, 0)).Y;

    // Get Composition variables.
    var scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(MainScroll);
    var stickyGridVisual = ElementCompositionPreview.GetElementVisual(StickyGrid);
    var compositor = scrollProperties.Compositor;

    // Basically, what the expression
    // "ScrollingProperties.Translation.Y > OffsetY ? 0 : OffsetY - ScrollingProperties.Translation.Y"
    // means is that -
    // When ScrollingProperties.Translation.Y > OffsetY, it means the scroller has yet to scroll to the sticky Grid, so
    // at this time we don't want to do anything, hence the return of 0;
    // when the expression becomes false, we need to offset the the sticky Grid on Y Axis by adding a negative value
    // of ScrollingProperties.Translation.Y. This means the result will forever be just OffsetY after hitting the top.
    var scrollingAnimation = compositor.CreateExpressionAnimation("ScrollingProperties.Translation.Y > OffsetY ? 0 : OffsetY - ScrollingProperties.Translation.Y");
    scrollingAnimation.SetReferenceParameter("ScrollingProperties", scrollProperties);
    scrollingAnimation.SetScalarParameter("OffsetY", offsetY);

    // Kick off the expression animation.
    stickyGridVisual.StartAnimation("Offset.Y", scrollingAnimation);
};

这里是 GitHub 上的一个工作演示.

Here is a working demo on GitHub.

这篇关于如何检查 UI 元素是否已到达 Windows Phone 中的页面顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:12