如何检查 UI 元素是否已到达 Windows Phone 中的页面顶部
本文关键字:Phone Windows 顶部 何检查 检查 是否 元素 UI | 更新日期: 2023-09-27 18:35:28
有一个页面有一个滚动查看器和一些本质上是动态的内容。在页面中间有一个网格。每当用户滚动页面并且网格到达页面顶部时,我都需要一个通知器。基本上,每当网格到达页面顶部时,我想使网格在顶部粘性。有什么方法可以在Windows Phone应用程序中实现这一点。我不想计算偏移量,因为页面顶部和网格之间的内容是动态的。
这曾经很难做到,但多亏了新的Windows Composition API,它现在相当简单。
假设我有一个名为 MainScroll
的ScrollViewer
,它承载着一个名为 StickyGrid
的Grid
,我想让后者在到达顶部后变得粘稠。
有带有注释的代码来解释它的作用。
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上的工作演示。