Search code examples
xamarin.formsswipeslidepan

How to get every pann gesture that happens


I have a pretty simple question but I can't find any answer about it.

I have an app and I would like to get a function called, each time that a Pan/Swipe/Slide gesture happen.

I know how does the layouts are organized, so it means I can't add a gesture on the main layout, but at the same time, it seems creepy to add this gesture to each elements...

Any idea?

Thank


Solution

  • I find something which isn't that bad, which can also raise an event or call a given Action<>

    public class PanContainer : ContentView
    {
        private double x, y;
    
        public PanContainer()
        {
            var panGesture = new PanGestureRecognizer();
            panGesture.PanUpdated += OnPanUpdated;
            GestureRecognizers.Add(panGesture);
            BackgroundColor = Color.Transparent;
        }
    
        private double valueX;
        private double valueY;
    
        private void OnPanUpdated(object sender, PanUpdatedEventArgs e)
        {
            if (e.TotalX == 0 && e.TotalX != valueX)
                Debug.WriteLine("The X pan value is [{0}]", valueX);
            valueX = e.TotalX;
            if (e.TotalY == 0 && e.TotalY != valueX)
                Debug.WriteLine("The Y pan value is [{0}]", valueY);
            valueY = e.TotalY;
        }
    }
    

    Just use it like it

    <ContentPage.Content>
        <AbsoluteLayout BackgroundColor="Black">
            <component:PanContainer AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1" AbsoluteLayout.LayoutFlags="All">
    
            </component:PanContainer>
        </AbsoluteLayout>
    </ContentPage.Content>
    

    and don't forget to include xmlns:component="clr-namespace:NAMESPACE.Sources.Components;assembly=NightLine"


    If you wanna raise an event or call a function, do it from private void OnPanUpdated(object sender, PanUpdatedEventArgs e) { .. }