在WPF中进行可移动控制

Ter*_*lis 8 wpf xaml movable

我有一个面板,在该面板中有几个矩形控件(控件vaires的数量)我希望用户能够在面板内移动控件,以便他们可以以最适合他们的方式安排控件.有没有人有任何我可以阅读的资源或简单的提示,让我走向正确的道路?

谢谢

Ter*_*lis 9

我想出了一种在拖动/移动样式中移动控件的简单方法......以下是步骤.

  1. 在控件中选择您希望成为移动区域的元素.这是一个区域,如果我用户按住鼠标,控件将移动.在我的例子中,它是控件顶部的矩形边框.
  2. 使用OnMouseDown事件将布尔值(在我的情况下为IsMoving)设置为true,将MouseUp事件设置为false
  3. 在第一个MouseDown事件上,使用以下代码设置一些Point属性(InitialPosition)

    if (FirstClick)
    {
         GeneralTransform transform = this.TransformToAncestor(this.Parent as Visual);
         Point StartPoint = transform.Transform(new Point(0, 0));
         StartX = StartPoint.X;
         StartY = StartPoint.Y;
         FirstClick = false;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 现在你有了起始位置,你需要获得相对于你的运动控制的鼠标位置.这样你最终不会点击标题的中间来移动它,它会立即将控件的左上角移动到鼠标指针位置.为此,请将此代码放在MouseDown事件中:

    Point RelativeMousePoint = Mouse.GetPosition(Header);
    RelativeX = RelativeMousePoint.X;
    RelativeY = RelativeMousePoint.Y;
    
    Run Code Online (Sandbox Code Playgroud)
  5. 现在你得到的控件来自(startX和STartY),鼠标在你的运动控制中的位置(RelativeX,RelativeY),我们只需要将控件移动到一个新位置!这样做有几个步骤.首先,你的控件需要有一个RenlateTransform,它是一个TranslateTransform.如果你不想在XAML中设置它,可以随意设置它this.RenderTransform = new TranslateTransform.

  6. 现在我们需要在RenderTransform上设置X和Y坐标,以便控件移动到新位置.以下代码实现了这一点

    private void Header_MouseMove(object sender, MouseEventArgs e)
    {
        if (IsMoving)
        {
            //Get the position of the mouse relative to the controls parent              
            Point MousePoint = Mouse.GetPosition(this.Parent as IInputElement );
            //set the distance from the original position
            this.DistanceFromStartX= MousePoint.X - StartX - RelativeX ;
            this.DistanceFromStartY= MousePoint.Y - StartY - RelativeY;
            //Set the X and Y coordinates of the RenderTransform to be the Distance from original position. This will move the control
            TranslateTransform MoveTransform = base.RenderTransform as TranslateTransform;
            MoveTransform.X = this.DistanceFromStartX;
            MoveTransform.Y = this.DistanceFromStartY;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

正如你可以猜到的,还有一些代码(变量声明等),但这应该是你需要的所有开始:)快乐的编码.

编辑:
您可能遇到的一个问题是,这允许您将控件移出其父控件的区域.这里有一些快速而脏的代码来解决这个问题......

if ((MousePoint.X + this.Width - RelativeX > Parent.ActualWidth) ||
     MousePoint.Y + this.Height - RelativeY > Parent.ActualHeight ||
     MousePoint.X - RelativeX  < 0 || 
     MousePoint.Y - RelativeY  < 0)
{
    IsMoving = false;
    return;
}
Run Code Online (Sandbox Code Playgroud)

在实际移动发生之前,将此代码放在MouseMove事件中.这将检查控件是否试图超出父控件的范围.该IsMoving = false命令将使控件退出运动模式.这意味着用户将需要再次单击移动区域以尝试移动控件,因为它将在边界处停止.如果您希望控件自动继续移动,只需取出该线,控件将在返回合法区域后立即跳回光标.