我有一个简单的应用程序来绘制椭圆、线条和矩形。
代码:
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
if(figura == "linia")
{
linia = new Line
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
canvas.Children.Add(linia);
}
if (figura == "kwadrat")
{
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
Canvas.SetLeft(rect, startPoint.X);
Canvas.SetTop(rect, startPoint.X);
canvas.Children.Add(rect);
}
else if (figura == "kolko")
{
circ = new Ellipse
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
Canvas.SetLeft(circ, startPoint.X);
Canvas.SetTop(circ, startPoint.X);
canvas.Children.Add(circ);
}
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released || rect == null && circ == null && linia == null)
return;
var pos = e.GetPosition(canvas);
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
if(figura == "linia")
{
linia.X1 = startPoint.X;
linia.Y1 = startPoint.Y;
linia.X2 = pos.X;
linia.Y2 = pos.Y;
}
if (figura == "kwadrat")
{
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
if (figura == "kolko")
{
circ.Width = w;
circ.Height = h;
Canvas.SetLeft(circ, x);
Canvas.SetTop(circ, y);
}
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
rect = null;
circ = null;
}
现在我想对对象做一些事情,比如调整大小、移动等。当它们被鼠标点击时。我不知道如何找到被鼠标单击的对象。你能帮助我吗 ?