从条形WPF拖动窗口

时间:2016-06-10 15:58:56

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

我正在尝试为我的窗口构建自定义栏,并且我正在处理拖放代码,但它没有按预期工作。
它运作良好'因为它拖动了窗口,但如果我用鼠标快一点,它就会离开DragBar,它就会停止工作。在Windows Forms中,它几乎可以顺利运行,但在WPS上我遇到了这个问题。

    private Point mouseDown;    //Mouse on click
    private Point windowDown;   //Window on click
    private Vector mouseOffset; //Mouse on click - Mouse Actual Position
    private bool drag;          //If drag is happening (between mouse Down and mouse Up)

    private void DragBar_MouseDown(object sender, MouseButtonEventArgs e)
    {
        drag = true;
        mouseDown  = PointToScreen(Mouse.GetPosition(this));
        windowDown = new Point(this.Left, this.Top);
    }

    private void DragBar_MouseMove(object sender, MouseEventArgs e)
    {
        if (drag)
        {
            mouseOffset = PointToScreen(Mouse.GetPosition(this)) - mouseDown;
            this.Left = windowDown.X + mouseOffset.X;
            this.Top  = windowDown.Y + mouseOffset.Y;
        }
    }
    private void DragBar_MouseUp(object sender, MouseButtonEventArgs e)
    {
        drag = false;
    }

~~编辑___________________
使用这种方法可以获得更高的效率,但仍然会失去抓地力'当鼠标太快时 @Cody Gray我会继续从事件e获得良好的实践,但它似乎没有帮助解决问题

    private Point mouseDown;    //Mouse position relative to form
    private bool drag = false;  //If drag is happening (between mouse Down and mouse Up)

    private void DragBar_MouseDown(object sender, MouseButtonEventArgs e)
    {
        drag = true;
        mouseDown = e.GetPosition(this);
    }

    private void DragBar_MouseMove(object sender, MouseEventArgs e)
    {
        if (drag)
        {
            this.Left = PointToScreen(e.GetPosition(this)).X - mouseDown.X;
            this.Top  = PointToScreen(e.GetPosition(this)).Y - mouseDown.Y;
        }
    }
    private void DragBar_MouseUp(object sender, MouseButtonEventArgs e)
    {
        drag = false;
    }

1 个答案:

答案 0 :(得分:0)

我工作的家伙指出,有一种更简单的方法可以做到这一点。

在你的窗口中的xaml

      <Border x:Name="DragBar" 
           Height="100"
           MouseLeftButtonDown="DragBar_MouseLeftButtonDown" />

背后的代码

    private void DragBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.DragMove();
    }

完成。