[英]Draggable control in WPF?
I'm kind of new to WPF although I have some experience in Forms, and I decided to finally try to figure out how to use WPF. So When I got to draggable controls, this is the code I came up with (I attempted to change it to work with WPF but the control just twitches everywhere):我是 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);
}
}
Alternative:选择:
Microsoft.Xaml.Behaviors.Wpf
Microsoft.Xaml.Behaviors.Wpf
xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"
<Grid>
<behaviors:Interaction.Behaviors>
<behaviors:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</behaviors:Interaction.Behaviors>
</Grid>
If you want to do it by hands use following algorithm:如果您想手动使用以下算法:
MouseDown
event: Save Mouse position , TopLeft position of control, and delta(offset) of these coordinates, and set some boolean field flag eg.MouseDown
事件上:保存Mouse position ,控件的TopLeft position和这些坐标的 delta(offset),并设置一些 boolean 字段标志,例如。 IsDragStartted
to true. IsDragStartted
为真。 On MouseMove
check that drag started and use Mouse position and offset to calculate the new value of TopLeft position of control在
MouseMove
上检查是否开始拖动并使用Mouse position和 offset 来计算控件的TopLeft position的新值
On MouseUp
event set IsDragStartted
to false在
MouseUp
事件IsDragStartted
设置为 false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.