Search code examples
c#windowsxamluwpstackpanel

How to drag a stackpanel (not drag-drop) like dragging a application window in windows


I am making a uwp App, which is a widgets app, and if the user wants to reposition the widgets, (each widget is a stackpanel with content), the stackpanel should move according to the mouse, just like dragging an application window in windows, please help me I have been trying so much but got nothing!


Solution

  • To make the StackPanel movable, you have to add these two events to it.

    PointerPressed="StackPanel_PointerPressed"
    PointerMoved="StackPanel_PointerMoved"
    

    In your C# code you have to create a variable and also add a using:

    using Windows.Foundation;
    
    private Point MouseDownLocation;
    

    The event StackPanel_PointerPressed:

    private void StackPanel_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        if (sender is StackPanel sp)
        {
            if (e.GetCurrentPoint(sp).Properties.IsLeftButtonPressed)
            {
                MouseDownLocation.Y = e.GetCurrentPoint(sp).Position.Y;
                MouseDownLocation.X = e.GetCurrentPoint(sp).Position.X;
            }
        }
    }
    

    And the event StackPanel_PointerMoved:

    private void StackPanel_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        if (sender is StackPanel sp)
        {
            if (e.GetCurrentPoint(sp).Properties.IsLeftButtonPressed)
            {
                var MarginLeft = e.GetCurrentPoint(sp).Position.X + sp.Margin.Left - MouseDownLocation.X;
                var MarginTop = e.GetCurrentPoint(sp).Position.Y + sp.Margin.Top - MouseDownLocation.Y;
                sp.Margin = new Thickness(MarginLeft, MarginTop, sp.Margin.Right, sp.Margin.Bottom);
            }
        }
    }