我正在编写一个silverlight应用程序,有一个要求,我需要在图像上绘制矩形并随着鼠标移动一起移动。我可以通过按住鼠标左键来移动矩形,但现在我需要移动而不需要单击或按住鼠标左键单击。
我见过很多例子,但是他们都在左键鼠标上实现了移动的形状和矩形,这绝对不是我的要求。
我尝试了很多方法,但无法做到正确。以下是我目前所做的代码。任何建议都会受到欢迎。
XAML
<Canvas x:Name="draw" Grid.Column="0" Background="Transparent"
Margin="0,0,0,150" Grid.RowSpan="2">
<Rectangle x:Name="SquareBlue" Width="100" Height="100" Canvas.Top="155" Canvas.Left="268" Fill="Transparent" Stroke="Black" StrokeThickness="2" />
</Canvas>
<Image x:Name="myImage" Height="100"/>
<TextBox x:Name="X" Margin="0,0,110,0"></TextBox>
<TextBox x:Name="Y" Margin="0,0,110,0"/>
<Image x:Name="pictureBox1" Height="100"/>
代码背后
Boolean isMouseCaptured;
Double mouseX;
Double mouseY;
Int32 zIndex = 0;
private void Shape_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Shape s = sender as Shape;
isMouseCaptured = false;
s.ReleaseMouseCapture();
mouseY = -1;
mouseX = -1;
}
private void Shape_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Shape s = sender as Shape;
mouseY = e.GetPosition(null).Y;
mouseX = e.GetPosition(null).X;
isMouseCaptured = true;
s.CaptureMouse();
s.SetValue(Canvas.ZIndexProperty, zIndex);
zIndex++;
}
private void Shape_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseCaptured)
{
Shape s = sender as Shape;
double deltaY = e.GetPosition(null).Y - mouseY;
double deltaX = e.GetPosition(null).X - mouseX;
double newTop = deltaY + (double)s.GetValue(Canvas.TopProperty);
double newLeft = deltaX + (double)s.GetValue(Canvas.LeftProperty);
s.SetValue(Canvas.TopProperty, newTop);
s.SetValue(Canvas.LeftProperty, newLeft);
mouseY = e.GetPosition(null).Y;
mouseX = e.GetPosition(null).X;
X.Text = mouseX.ToString();
Y.Text = mouseY.ToString();
}
答案 0 :(得分:0)
您可能希望在触发Shape_MouseMove时考虑捕获的形状。 然后,在画布/窗口上的每个鼠标移动都会将形状移动到鼠标光标周围。 然后你必须决定何时发布它: