如何像在 Windows 中拖动应用程序窗口一样拖动堆栈面板(而不是拖放)
Posted
技术标签:
【中文标题】如何像在 Windows 中拖动应用程序窗口一样拖动堆栈面板(而不是拖放)【英文标题】:How to drag a stackpanel (not drag-drop) like dragging a application window in windows 【发布时间】:2021-11-19 17:46:27 【问题描述】:我正在制作一个uwp App,它是一个widgets应用程序,如果用户想要重新定位widgets,(每个widget都是一个带有内容的stackpanel),stackpanel应该根据鼠标移动,就像拖动一个应用程序一样windows中的windows,请帮帮我,我一直在尝试,但一无所获!
【问题讨论】:
【参考方案1】:要使 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);
【讨论】:
好吧,它不起作用,它更像是调整堆栈面板的大小。【参考方案2】:我碰巧解决了这个问题,虽然没有@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!
【讨论】:
以上是关于如何像在 Windows 中拖动应用程序窗口一样拖动堆栈面板(而不是拖放)的主要内容,如果未能解决你的问题,请参考以下文章