鼠标单击画布中的对象

时间:2013-04-22 15:58:39

标签: c# wpf

我有简单的应用程序,绘制椭圆,线条和矩形。

代码:

 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;
    }

现在我想用像调整大小,移动等对象做一些事情。当它们被鼠标点击时。我不知道我怎么能找到被鼠标点击的对象。你能救我吗?

2 个答案:

答案 0 :(得分:3)

e.OriginalSource会为您提供实际点击的控件。

答案 1 :(得分:2)

使用RoutedEvent.Source属性。

if (e.Source is Rectangle)
{
}
else if (e.Source is Ellipse)
{
}
else if (e.Source is Line)
{
}