本文說明如何使用 XAML ScrollViewer 和 ExpressionAnimations 來建立動態輸入驅動動作體驗。
先決條件
在這裡,我們假設您已熟悉下列文章中討論的概念:
為什麼要建置在 ScrollViewer 之上?
一般而言,您可以使用現有的 XAML ScrollViewer 來建立應用程式內容的可捲動和可縮放表面。 隨著 Fluent Design 語言的推出,您現在也應該專注於如何使用卷動或縮放表面的動作來驅動其他動作體驗。 例如,使用卷動來驅動背景模糊動畫,或調整「黏性標頭」(固定在頁面頂部的標題)的位置。
在這些案例中,您會利用卷動和縮放等行為或作體驗,讓應用程式的其他部分更具動態性。 接著,這些可讓應用程式感覺更具凝聚力,使終端使用者眼中的體驗變得更加令人難忘。 藉由讓應用程式 UI 更令人難忘的方式,終端使用者會更頻繁且長時間地與應用程式互動。
您可以在 ScrollViewer 之上建置什麼?
您可以利用 ScrollViewer 的位置來建置一些動態體驗:
- 視差效果 – 利用 ScrollViewer 的位置,以相對於捲動位置的速率移動背景或前景內容。
- StickyHeaders – 使用 ScrollViewer 的位置來建立動畫效果,並將標頭「貼上」至位置
- Input-Driven 效果 - 使用 Scrollviewer 的位置來動畫處理組合效果,例如模糊效果。
一般而言,藉由參考具有 ExpressionAnimation 的 ScrollViewer 位置,您可以建立動態變更相對於卷動數量的動畫。
使用 ScrollViewerManipulationPropertySet
若要使用 XAML ScrollViewer 建立這些動態體驗,您必須能夠參考動畫中的捲動位置。 這是透過從名為 ScrollViewerManipulationPropertySet 的 XAML ScrollViewer 中存取 CompositionPropertySet 來完成。 ScrollViewerManipulationPropertySet 包含稱為 Translation 的單一 Vector3 屬性,可讓您存取 ScrollViewer 的捲動位置。 然後,您可以在 ExpressionAnimation 中像任何其他 CompositionPropertySet 一樣參考這個 。
入門的一般步驟:
- 透過 ElementCompositionPreview 存取 ScrollViewerManipulationPropertySet。
ElementCompositionPreview.GetScrollViewerManipulationPropertySet(ScrollViewer scroller)
- 建立 ExpressionAnimation,參考 PropertySet 中的 Translation 屬性。
- 別忘了設定參考參數!
- 使用 ExpressionAnimation 設置 CompositionObject 的屬性。
備註
建議您將 GetScrollViewerManipulationPropertySet 方法傳回的 PropertySet 指派給類別變數。 這可確保屬性集不會被垃圾收集清除,因此不會對其所參考的 ExpressionAnimation 產生任何影響。 ExpressionAnimations 不會對方程式中使用的任何對象維持強參照。
範例
讓我們來看看上面顯示的視差範例是如何組成的。 供參考,應用程式的所有原始程式碼皆在 GitHub 上的 Window UI Dev Labs 儲存庫中。
第一件事是取得 ScrollViewerManipulationPropertySet 的參考。
_scrollProperties =
ElementCompositionPreview.GetScrollViewerManipulationPropertySet(myScrollViewer);
下一個步驟是建立 ExpressionAnimation,以定義利用 ScrollViewer 滾動位置的方程式。
_parallaxExpression = compositor.CreateExpressionAnimation();
_parallaxExpression.SetScalarParameter("StartOffset", 0.0f);
_parallaxExpression.SetScalarParameter("ParallaxValue", 0.5f);
_parallaxExpression.SetScalarParameter("ItemHeight", 0.0f);
_parallaxExpression.SetReferenceParameter("ScrollManipulation", _scrollProperties);
_parallaxExpression.Expression = "(ScrollManipulation.Translation.Y + StartOffset - (0.5 * ItemHeight)) * ParallaxValue - (ScrollManipulation.Translation.Y + StartOffset - (0.5 * ItemHeight))";
備註
您也可以利用 ExpressionBuilder 協助程式類別來建構此相同的運算式,而不需要字串:
var scrollPropSet = _scrollProperties.GetSpecializedReference<ManipulationPropertySetReferenceNode>(); var parallaxValue = 0.5f; var parallax = (scrollPropSet.Translation.Y + startOffset); _parallaxExpression = parallax * parallaxValue - parallax;
最後,您採用此 ExpressionAnimation,並將目標設為您想要執行視差效果的視覺物件。 在這種情況下,這是清單中每個項目的圖片。
Visual visual = ElementCompositionPreview.GetElementVisual(image);
visual.StartAnimation("Offset.Y", _parallaxExpression);