【问题标题】:Draggable control in WPF?WPF中的可拖动控件?
【发布时间】:2012-04-05 04:13:46
【问题描述】:

我对 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);
    }
}

【问题讨论】:

    标签: c# wpf xaml drag-and-drop


    【解决方案1】:

    你想用adorners实现拖拽、调整大小、旋转等

    【讨论】:

    • 我真的很想从头开始编写代码,比如只使用事件和边距等基本内容
    • 在拖动控件时,这确实不是一个聪明的主意,这是一项非常“不平凡”的任务。否则 WPF 不会一开始就引入装饰器的概念:)
    • 装饰器确实是要走的路
    【解决方案2】:

    here 是 MSDN 上关于此事的一篇相当不错的文章。此外,在 Google 上进行快速搜索会发现真正的聚宝盆可供您享受 DnD 用餐乐趣。

    【讨论】:

      【解决方案3】:

      替代方案:

      1. 安装 NuGet 包: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>
      

      【讨论】:

      • 拖动工作正常,但它没有提供任何选项来为拖动的控件设置任何有效负载。
      【解决方案4】:

      如果您想手动操作,请使用以下算法:

      1. MouseDown 事件上:保存鼠标位置、控件的TopLeft 位置,以及这些坐标的增量(偏移),并设置一些布尔字段标志,例如。 IsDragStartted 为真。
      2. MouseMove 上检查是否开始拖动并使用鼠标位置 和偏移来计算控件TopLeft 位置 的新值

        李>
      3. 开启MouseUp 事件将IsDragStartted 设置为false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-18
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 2012-12-04
        • 1970-01-01
        • 2011-01-02
        • 1970-01-01
        相关资源
        最近更新 更多