C# 锁定区域内的拖动|仅水平垂直移动|拖动预览事件
我有一个C# 锁定区域内的拖动|仅水平垂直移动|拖动预览事件,c#,wpf,C#,Wpf,我有一个WindowContainer类,其中所有ChildWindows都会自动注册。想法是,所有ChildWindows都被“锁定”在WindowContainer内,您不能将它们移动/拖动到该区域之外 ChildWindow继承自Window 我已经找到了一个可行的解决方案: C#代码段 所以现在我只调用setdragmoveare()如果我的ChildWindow应该被锁定在我的WindowContainer中。 我用下面的代码提取这个区域的信息 WorkingArea = Window
WindowContainer
类,其中所有ChildWindows
都会自动注册。想法是,所有ChildWindows
都被“锁定”在WindowContainer
内,您不能将它们移动/拖动到该区域之外
ChildWindow
继承自Window
我已经找到了一个可行的解决方案:
C#代码段
所以现在我只调用setdragmoveare()
如果我的ChildWindow
应该被锁定在我的WindowContainer
中。
我用下面的代码提取这个区域的信息
WorkingArea = WindowContainer.TransformToAncestor(System.Windows.Application.Current.MainWindow).TransformBounds(new Rect(new Point(0, 0), WindowContainer.RenderSize));
默认情况下,它是否锁定在屏幕的内部(请参见\u onload
)
工作方案预览
我为您找到了一个解决方案。如果要自定义移动,则不能使用DragMove
方法。相反,您必须自己实现此功能,覆盖以下三个功能:OnMouseLeftButtonDown
、OnMouseMove
和OnMouseLeftButtonUp
。
我已经实现了类似的功能:
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
anchorPoint = e.GetPosition(this);
inDrag = true;
CaptureMouse();
e.Handled = true;
}
其中,anchorPoint
是我用于绑定窗口位置的点,inDrag
是私有布尔值,CaptureMouse
是UIElement
方法
然后:
protected override void OnMouseMove(MouseEventArgs e)
{
if (inDrag)
{
Point currentPoint = e.GetPosition(this);
this.Left = this.Left + currentPoint.X - anchorPoint.X;
/*this.Top = this.Top + currentPoint.Y - anchorPoint.Y*/; // this is not changing in your case
anchorPoint = currentPoint;
}
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (inDrag)
{
ReleaseMouseCapture();
inDrag = false;
e.Handled = true;
}
}
其中ReleaseMouseCapture
是UIElement
方法。
我认为它应该对您有所帮助。没有鼠标拖动事件,因为拖动与鼠标无关。因此,为什么找不到有关拖动的鼠标事件。拖动窗口是窗口的行为,而不是鼠标的行为。您可以通过观察和跟踪鼠标坐标以及鼠标按钮的状态来实现所需的特定拖动功能。这些信息是由鼠标事件提供的。我猜(我在这里只是猜测),您真正想要的是在特定区域捕获鼠标,对吗?(即,当窗口触及区域边界时,鼠标不应与窗口断开连接并进一步移动)否,我想将ChildWindow保持在WindowContainer内。例如,键盘(预览)不能移到屏幕外,而且总是在可见区域。这听起来像是肯定的。或者你真的想限制窗口的移动,但不限制鼠标的移动(在拖动过程中)?A你说得对!我误解你了,嘿,尼科。谢谢你的回答!这几乎是我需要的解决方案。如果我已经完全实现了,我会更新我的帖子。
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
anchorPoint = e.GetPosition(this);
inDrag = true;
CaptureMouse();
e.Handled = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (inDrag)
{
Point currentPoint = e.GetPosition(this);
this.Left = this.Left + currentPoint.X - anchorPoint.X;
/*this.Top = this.Top + currentPoint.Y - anchorPoint.Y*/; // this is not changing in your case
anchorPoint = currentPoint;
}
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (inDrag)
{
ReleaseMouseCapture();
inDrag = false;
e.Handled = true;
}
}