繁体   English   中英

WPF 中的可拖动控件?

[英]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);
    }
}

你想使用装饰器来实现拖动、调整大小、旋转等。

选择:

  1. 安装 NuGet package: Microsoft.Xaml.Behaviors.Wpf
  2. 将其添加到根元素:
xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"
  1. 只需将它放在您的元素中:
<Grid>
    <behaviors:Interaction.Behaviors>
        <behaviors:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </behaviors:Interaction.Behaviors>
</Grid>

如果您想手动使用以下算法:

  1. MouseDown事件上:保存Mouse position ,控件的TopLeft position和这些坐标的 delta(offset),并设置一些 boolean 字段标志,例如。 IsDragStartted为真。
  2. MouseMove上检查是否开始拖动并使用Mouse position和 offset 来计算控件的TopLeft position的新值

  3. MouseUp事件IsDragStartted设置为 false

是一篇关于 MSDN 上此事的非常好的文章。 此外,在 Google 上快速搜索会发现真正的聚宝盆,供您享受 DnD 用餐乐趣。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM