Question

I'm trying to delete some lines I have drawn on my canvas, and my idea was to use the coordinates of the Line controls from Canvas.Children.

My initial code looked like this:

    var ax = Mouse.GetPosition(Canvas).X;
    int mx1 = (int)ax - (eraserSize / 2);
    int mx2 = (int)ax + (eraserSize / 2);
    var ay = Mouse.GetPosition(Canvas).Y;
    int my1 = (int)ay - (eraserSize / 2);
    int my2 = (int)ay + (eraserSize / 2);

foreach(Line l in Canvas.Children)
{
    if((l.X1 < mx1 && lX2 > mx2) && (l.Y1 < my1 && lY2 > my2))
    {
        Canvas.Children.Remove(l);
    }
}

But of course it doesn't work since there are other controls that it cannot cast to Line.

I tried using if(l.Name == "LineName") to put these in a Line[] or Control[] but nothing works, and I'm not sure what else to try, other then just painting over it...

Was it helpful?

Solution

foreach(var child in Canvas.Children)
{
    var l = child as Line;
    if(l != null && (l.X1 < mx1 && lX2 > mx2) && (l.Y1 < my1 && lY2 > my2))
    {
        // You can't remove item from collection you enumerate thru
        // Canvas.Children.Remove(l);
        LinesToDelete.Add(l);
    }
}

Than you can simple remove all lines that got to LinesToDelete

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top