鼠标单击画布中的对象

本文关键字:对象 布中 单击 鼠标 | 更新日期: 2023-09-27 18:10:17

我有一个简单的应用程序,可以绘制椭圆、直线和矩形。

代码:

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

现在我想对对象做一些事情,比如调整大小,移动等。当它们被鼠标点击时。我不知道如何找到被鼠标点击过的对象。你能帮我吗?

鼠标单击画布中的对象

e.OriginalSource将获得实际单击的控件

使用RoutedEvent。源属性。

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