首页 > 解决方案 > 如何像在 Windows 中拖动应用程序窗口一样拖动堆栈面板(而不是拖放)

问题描述

我正在制作一个uwp App,它是一个小部件应用程序,如果用户想要重新定位小部件,(每个小部件都是一个带有内容的堆栈面板),堆栈面板应该根据鼠标移动,就像在windows中拖动应用程序窗口一样,请帮助我,我一直在尝试,但一无所获!

标签: c#windowsxamluwpstackpanel

解决方案


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

推荐阅读