Search code examples
c#wpfswipeswipe-gesture

How to create left and right swipes in WPF using Mouse?


I'm very new to C#.So, i'm trying create a simple swipe function in my WPF where if i swipe left or right, it goes to another wpf window. Please help me! I cannot find much resources online.

So my question is how to swipe using mouse in wpf application, so that i can switch between pages/window using mouse swipe.

Sketch

I'm just trying to do like an image Carousel. I have so far followed this WPF image swipe to change image like in iOS But, it doesn't swipe but zooms in and out when mouse is moved.


Solution

  • I am Using Pages but you can use window also.

    1st. Create two Pages LeftPage.xaml, and RightPage.Xaml and following code to MainWindow.xaml and MainWindows.xaml.cs

    XAML

    MainWindow

    <Window x:Class="SOWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        
        xmlns:local="clr-namespace:SOWPF"
        mc:Ignorable="d" 
        Title="MainWindow" Height="450" Width="800"
        MouseDown="Window_MouseDown" MouseMove="Window_MouseMove">
    <Grid>
        <Frame x:Name="MainFrame" NavigationUIVisibility="Hidden" />
    </Grid>
    

    C#

    public partial class MainWindow : Window
    {
        protected Point SwipeStart;
        public MainWindow()
        {
            InitializeComponent();
            MainFrame.Source = new Uri("LeftPage.xaml", UriKind.RelativeOrAbsolute);
        }
    
        private void Window_MouseDown(object sender, MouseEventArgs e)
        {
            SwipeStart = e.GetPosition(this);
        }
    
        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var Swipe = e.GetPosition(this);                
    
                //Swipe Left
                if (SwipeStart != null && Swipe.X > (SwipeStart.X + 200))
                {
                    // OR Use Your Logic to switch between pages.
                    MainFrame.Source = new Uri("LeftPage.xaml", UriKind.RelativeOrAbsolute);
                }
    
                //Swipe Right
                if (SwipeStart != null && Swipe.X < (SwipeStart.X - 200))
                {
                    // OR Use Your Logic to switch between pages.
                    MainFrame.Source = new Uri("RightPage.xaml", UriKind.RelativeOrAbsolute);
                }
            }
            e.Handled = true;
        }
    }
    

    Demo