我有繪製橢圓,線條和矩形的簡單應用程序。鼠標在畫布上單擊對象
代碼:
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;
}
現在我想做的事情與像大小調整對象的東西,移動等等。當他們被鼠標單擊。我不知道如何找到被鼠標點擊的對象。你可以幫我嗎 ?
在你自己做所有事情之前。考慮使用[Thumb](http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx)控件,該控件完美適用於調整大小和移動對象。除此之外,爲什麼畫布需要了解這些項目?你應該檢查Panel和ItemsControl是什麼。 – dowhilefor 2013-04-22 16:04:37
閱讀此:http://msdn.microsoft.com/en-us/library/ms752097.aspx – mlemay 2013-04-22 16:05:08