/
ParallaxBehavior.cs
82 lines (69 loc) · 3.03 KB
/
ParallaxBehavior.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using Composition.UI.Extensions;
using Microsoft.Xaml.Interactivity;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Xaml.Media.Animation;
namespace Composition.UI.Behaviors
{
public class ParallaxBehavior : Behavior<FrameworkElement>
{
/// <summary>
/// Gets or sets the element that will parallax while scrolling.
/// </summary>
public UIElement ParallaxContent
{
get { return (UIElement)GetValue(ParallaxContentProperty); }
set { SetValue(ParallaxContentProperty, value); }
}
public static readonly DependencyProperty ParallaxContentProperty = DependencyProperty.Register(
"ParallaxContent",
typeof(UIElement),
typeof(ParallaxBehavior),
new PropertyMetadata(null, OnParallaxContentChanged));
/// <summary>
/// Gets or sets the rate at which the ParallaxContent parallaxes.
/// </summary>
public double ParallaxMultiplier
{
get { return (double)GetValue(ParallaxMultiplierProperty); }
set { SetValue(ParallaxMultiplierProperty, value); }
}
public static readonly DependencyProperty ParallaxMultiplierProperty = DependencyProperty.Register(
"ParallaxMultiplier",
typeof(double),
typeof(ParallaxBehavior),
new PropertyMetadata(0.3d));
protected override void OnAttached()
{
base.OnAttached();
AssignParallax();
}
private void AssignParallax()
{
if (ParallaxContent == null) return;
if (AssociatedObject == null) return;
var scroller = AssociatedObject as ScrollViewer;
if (scroller == null)
{
scroller = AssociatedObject.GetChildOfType<ScrollViewer>();
}
if (scroller == null) return;
CompositionPropertySet scrollerViewerManipulation = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scroller);
Compositor compositor = scrollerViewerManipulation.Compositor;
ExpressionAnimation expression = compositor.CreateExpressionAnimation(ParallaxMultiplier > 0
? "ScrollManipulation.Translation.Y * ParallaxMultiplier - ScrollManipulation.Translation.Y"
: "ScrollManipulation.Translation.Y * ParallaxMultiplier");
expression.SetScalarParameter("ParallaxMultiplier", (float)ParallaxMultiplier);
expression.SetReferenceParameter("ScrollManipulation", scrollerViewerManipulation);
Visual textVisual = ElementCompositionPreview.GetElementVisual(ParallaxContent);
textVisual.StartAnimation("Offset.Y", expression);
}
private static void OnParallaxContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var b = d as ParallaxBehavior;
b.AssignParallax();
}
}
}