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

Time:09-28

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!

CodePudding user response:

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);
        }
    }
}

CodePudding user response:

I happen to solve this, although it would have not been possible without the help of @FrozenAssassine, this is the code

  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;
                var MarginRight = e.GetCurrentPoint(sp).Position.X   -sp.Margin.Left 220 - MouseDownLocation.X;
                var MarginBottom = e.GetCurrentPoint(sp).Position.Y   -sp.Margin.Top 140 - MouseDownLocation.Y; 
                sp.Margin = new Thickness(MarginLeft, MarginTop, MarginRight, MarginBottom);
                
            }

just made some changes to the PointerMoved function, thank you so much FrozenAssassine!!

  • Related