SL4.鼠标拖动

利用鼠标响应事件,定位对象的坐标,以实现拖放功能

XAML:

             <Canvas Background="Yellow"  Height="195" Name="canvas1" Width="457">
<Ellipse MouseMove="ellipse1_MouseMove" MouseLeftButtonDown="ellipse1_MouseLeftButtonDown"
MouseLeftButtonUp
="ellipse1_MouseLeftButtonUp" Fill="Gold" Canvas.Left="118" Canvas.Top="59" Height="100" Name="ellipse1" Stroke="Black" StrokeThickness="3" Width="200" />
</Canvas>
<TextBlock Height="23" Name="tbkPoint" Text="" Width="319" />

  

XAML.CS:

        Point curPos;
bool mouseMoviing = false;
private void ellipse1_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element
= sender as FrameworkElement;
if(mouseMoviing)
{
double currX = e.GetPosition(null).X - curPos.X;
double currY = e.GetPosition(null).Y - curPos.Y;
element.SetValue(Canvas.TopProperty, currY
+ (double)element.GetValue(Canvas.TopProperty));
element.SetValue(Canvas.LeftProperty,
currX
+ (double)element.GetValue(Canvas.LeftProperty));
tbkPoint.Text
= "Ellipse 当前坐标:"+ curPos.X.ToString() + "," + curPos.Y.ToString();
curPos
= e.GetPosition(null);
}
}

private void ellipse1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element
= sender as FrameworkElement;
curPos
= e.GetPosition(null);
mouseMoviing
= true;
if(null!=element)
{
element.CaptureMouse();
element.Cursor
= Cursors.Hand;
}
}

private void ellipse1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element
= sender as FrameworkElement;
mouseMoviing
= false;
element.ReleaseMouseCapture();
curPos.X
= 0;
curPos.Y
= 0;
element.Cursor
= null;
}

  

你可能感兴趣的:(鼠标)