如何像在 windows 中拖动应用程序 window 一样拖动堆栈面板(不是拖放)

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

我正在制作一个uwp App,它是一个widgets app,如果用户想重新定位widgets,(每个widgets都是一个包含内容的stackpanel),stackpanel应该根据鼠标移动,就像拖动一样windows 中的一个应用程序 window,请帮助我,我已经尝试了很多,但一无所获!

要使 StackPanel 可移动,您必须向其添加这两个事件。

PointerPressed="StackPanel_PointerPressed"
PointerMoved="StackPanel_PointerMoved"

在您的 C# 代码中,您必须创建一个变量并添加一个 using:

using Windows.Foundation;

private Point MouseDownLocation;

事件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;
        }
    }
}

和事件 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);
        }
    }
}

我碰巧解决了这个问题,虽然没有@FrozenAssassine 的帮助是不可能的,这是代码

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

刚刚对 PointerMoved 函数做了一些修改,非常感谢 FrozenAssassine!!