![](/img/trans.png)
[英]wpf custom control: draggable/resizable rectangle within another rectangle
[英]Draggable control in WPF?
我是 WPF 的新手,虽然我在 Forms 方面有一些经验,但我决定最终尝试弄清楚如何使用 WPF。所以当我使用可拖动控件时,这是我想出的代码(我试图将其更改为与 WPF 一起使用,但控件到处都在抽动):
private void rectangle1_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed) {
double x = this.Left + (double)e.GetPosition(this).X - (double)rectangle1.Margin.Left;
double y = this.Top + (double)e.GetPosition(this).Y - (double)rectangle1.Margin.Top;
rectangle1.Margin = new Thickness(x, y, rectangle1.Margin.Right, rectangle1.Margin.Bottom);
}
}
你想使用装饰器来实现拖动、调整大小、旋转等。
选择:
Microsoft.Xaml.Behaviors.Wpf
xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"
<Grid>
<behaviors:Interaction.Behaviors>
<behaviors:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</behaviors:Interaction.Behaviors>
</Grid>
如果您想手动使用以下算法:
MouseDown
事件上:保存Mouse position ,控件的TopLeft position和这些坐标的 delta(offset),并设置一些 boolean 字段标志,例如。 IsDragStartted
为真。 在MouseMove
上检查是否开始拖动并使用Mouse position和 offset 来计算控件的TopLeft position的新值
在MouseUp
事件IsDragStartted
设置为 false
这是一篇关于 MSDN 上此事的非常好的文章。 此外,在 Google 上快速搜索会发现真正的聚宝盆,供您享受 DnD 用餐乐趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.