简体   繁体   中英

How to move control in panel by mouse

I can not move the border control while the mouse is outside the border cotnrol

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
  x:Class="WpfApplication2.MainWindow"
  x:Name="Window"
  Title="Window1"
  Width="346.5" Height="215" WindowStyle="SingleBorderWindow" >

    <Grid Name="stack" >

        <Border x:Name="btn" Width="50" Height="20" VerticalAlignment="Top" BorderThickness="1" BorderBrush="Black" Background="#FFF50000"
                MouseMove="btn_MouseMove" MouseDown="btn_MouseDown" MouseUp="btn_MouseUp"  />
    </Grid>
</Window> 

Code behind

bool state = false;
Point prePoint;

private void btn_MouseMove(object sender, MouseEventArgs e)
{
    if (state)
    {
        Point p = e.GetPosition(this);
        Point p2 = e.GetPosition(btn);
        btn.Margin = new Thickness(0, p.Y - p2.Y + p.Y - prePoint.Y, 0, 0);
        prePoint = e.GetPosition(this);
    }
}
private void btn_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (sender == btn)
    {
        prePoint = e.GetPosition(this);
        state = true;
    }
}

private void btn_MouseUp(object sender, MouseButtonEventArgs e)
{
    state = false;
}

Because mouse move event fires when mouse is in border control. I think you need add mouse move event for window not for border control

Just Capture the mouse when it is inside the border and release it after task is completed, else it will stick. OR acc. to your code it might be like this ->

bool state = false;
Point prePoint;

private void btn_MouseMove(object sender, MouseEventArgs e)
{
if (state)
{
    Point p = e.GetPosition(this);
    Point p2 = e.GetPosition(btn);
    btn.Margin = new Thickness(0, p.Y - p2.Y + p.Y - prePoint.Y, 0, 0);
    prePoint = e.GetPosition(this);
    // Capture Mouse here ! as far as i think. !!!
    Mouse.Capture(this.ColorPlane, CaptureMode.Element);
}
else
{
    // Release Mouse here ! as far as i think. !!!
    Mouse.Capture(null);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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