2

尽管我在 Forms 方面有一些经验,但我对 WPF 有点陌生,我决定最终尝试弄清楚如何使用 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);
    }
}
4

4 回答 4

5

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

于 2012-04-05T04:16:04.957 回答
2

是 MSDN 上关于此事的一篇相当不错的文章。此外,在 Google 上进行快速搜索会发现一个名副其实的聚宝盆,为您带来 DnD 用餐乐趣。

于 2012-04-05T04:36:40.430 回答
2

选择:

  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>
于 2021-05-26T09:07:42.467 回答
1

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

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

  3. 事件MouseUp设置IsDragStartted为假

于 2012-04-05T04:35:19.697 回答