C# WPF 拖动控件
本文关键字:控件 拖动 WPF | 更新日期: 2023-09-27 18:32:16
我可以移动Ellipse
但MouseCursor
和Ellipse
不匹配。我希望它们匹配。
XAML:
<Grid>
<Canvas Name="canvas" MouseMove="CanvasMouseMove" MouseLeftButtonUp="CanvasMouseLeftButtonUp" MouseLeftButtonDown="CanvasMouseLeftButtonDown" >
<Ellipse Name="ellispe" Canvas.Top="0" Canvas.Left="0" Fill="#FFF4F4F5" Height="100" Stroke="Black" VerticalAlignment="Top" Width="100" />
</Canvas>
</Grid>
代码隐藏:
Point mousepoint;
private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if(canvas.CaptureMouse())
{
mousepoint = e.GetPosition(canvas);
}
}
private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
canvas.ReleaseMouseCapture();
}
private void CanvasMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var e_point = e.GetPosition(canvas);
var offset = e_point - mousepoint;
mousepoint = e_point;
var elposition = e.GetPosition(ellispe);
Canvas.SetLeft(ellispe, Canvas.GetLeft(ellispe) + offset.X );
Canvas.SetTop(ellispe, Canvas.GetTop(ellispe) + offset.Y );
}
}
<Canvas x:Name="canvas" MouseMove="canvas_MouseMove_1">
<Ellipse x:Name="ellipse" MouseLeftButtonDown="ellipse_MouseLeftButtonDown_1" MouseLeftButtonUp="ellipse_MouseLeftButtonUp_1" Fill="#FFB63636" Width="100" Height="100" Canvas.Left="198" Canvas.Top="94" />
</Canvas>
法典
Point p = new Point();
private void ellipse_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
ellipse.CaptureMouse();
p.X = e.GetPosition(canvas).X - Canvas.GetLeft(ellipse);
p.Y = e.GetPosition(canvas).Y - Canvas.GetTop(ellipse);
Debug.WriteLine(p.X + " : " + p.Y);
}
private void canvas_MouseMove_1(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var e_point = e.GetPosition(canvas);
Debug.WriteLine(e_point.X + " : " + p.X);
Canvas.SetLeft(ellipse, e_point.X - p.X);
Canvas.SetTop(ellipse, e_point.Y - p.Y);
}
}
private void ellipse_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
{
ellipse.ReleaseMouseCapture();
}