简体   繁体   English

WPF 中的可拖动控件?

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

You want to use adorners to achieve dragging, resizing, rotating, etc.你想使用装饰器来实现拖动、调整大小、旋转等。

Alternative:选择:

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

If you want to do it by hands use following algorithm:如果您想手动使用以下算法:

  1. On 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为真。
  2. On MouseMove check that drag started and use Mouse position and offset to calculate the new value of TopLeft position of controlMouseMove上检查是否开始拖动并使用Mouse position和 offset 来计算控件的TopLeft position的新值

  3. On MouseUp event set IsDragStartted to falseMouseUp事件IsDragStartted设置为 false

here is a pretty good article on the matter on MSDN. 是一篇关于 MSDN 上此事的非常好的文章。 also, a quick search on Google revealse a veritable cornucopia of choices for you DnD dining pleasure.此外,在 Google 上快速搜索会发现真正的聚宝盆,供您享受 DnD 用餐乐趣。

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

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