Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Last active December 1, 2018 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/4ecee19348137be9864f62f3e6057c8f to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/4ecee19348137be9864f62f3e6057c8f to your computer and use it in GitHub Desktop.
Fading ListView or GridView Header
public class FadeHeaderBehavior : Behavior<FrameworkElement>
{
public static readonly DependencyProperty HeaderElementProperty = DependencyProperty.Register(
"HeaderElement", typeof(UIElement), typeof(FadeHeaderBehavior), new PropertyMetadata(null, PropertyChangedCallback));
public UIElement HeaderElement
{
get { return (UIElement) GetValue(HeaderElementProperty); }
set { SetValue(HeaderElementProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssignFade();
}
private void AssignFade()
{
//if we're running on earlier than 10586
if (!ApiInformation.IsMethodPresent("Windows.UI.Xaml.Hosting.ElementCompositionPreview", nameof(ElementCompositionPreview.GetScrollViewerManipulationPropertySet)))
return;
if (AssociatedObject == null) return;
var scroller = AssociatedObject as ScrollViewer ?? AssociatedObject.GetChildOfType<ScrollViewer>();
if (scroller == null) return;
var scrollerViewerManipulation = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scroller);
var compositor = scrollerViewerManipulation.Compositor;
//---- expression animation for opacity -----//
//I use the scroller's offset and the header's height to calculate the opacity percentage and clamp it at 100%
var opacityExpression = compositor.CreateExpressionAnimation("Clamp(1 - (-ScrollManipululation.Translation.Y / HeaderHeight), 0, 1)");
//mandatory for using the Scrollviewer
opacityExpression.SetReferenceParameter("ScrollManipululation", scrollerViewerManipulation);
//pass in the height of the header as a Scalar
opacityExpression.SetScalarParameter("HeaderHeight", (float)HeaderElement.RenderSize.Height);
//---------begin animating----------//
var targetElement = ElementCompositionPreview.GetElementVisual(HeaderElement);
targetElement.StartAnimation("Opacity", opacityExpression);
}
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var b = d as FadeHeaderBehavior;
b?.AssignFade();
}
}
@LanceMcCarthy
Copy link
Author

This behavior will use the height of the header element to calculate the perfect opacity fade out. This means that as you scroll up, the header will hit 0% Opacity just as it scrolls off screen. To see this in action watch this Vine recording of a ListView with complex header.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment