Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rectangle/element in wpf

I draw SQUARE and other shapes in WPF. Like that,

 private Rect DrawSquare(Rect bounds, InkCanvas canvas)
    {
        Rectangle recta = new Rectangle();
        recta.Stroke = Brushes.Black;
        //recta.Fill = Brushes.Blue;
        recta.StrokeThickness = 4;
        recta.Width = bounds.Width;
        recta.Height = bounds.Height;
        InkCanvas.SetLeft(recta, bounds.Left);
        InkCanvas.SetRight(recta, bounds.Right);
        InkCanvas.SetTop(recta, bounds.Top);
        canvas.Children.Add(recta);
        return bounds;
    }

and i can delete random lines with that

private void myInkCanvas_SelectionChanging(object sender, InkCanvasSelectionChangingEventArgs e)
        {
            else if (toolbarMode == ToolbarMode.Delete)
            {
                myInkCanvas.Strokes.Erase(e.GetSelectedStrokes().GetBounds()); //can delete random lines
                ReadOnlyCollection<UIElement> elements = e.GetSelectedElements();
                foreach (UIElement element in elements)
                {
                    /*String ShapeName = ((System.Windows.Media.Visual)(element)).ToString();
                    if (ShapeName.Contains("Rectangle"))
                    {
                        Rectangle recta = (Rectangle)element;
                        recta.Fill = Brushes.Blue;
                    }*/
                    myInkCanvas.Children.Remove(element); //cant delete shapes!!?
                }
            }
    }

I can delete random lines but i cant delete shapes

how can i?

like image 946
Tayfun Yaşar Avatar asked Apr 30 '26 12:04

Tayfun Yaşar


1 Answers

You are using a foreach loop over the elements collection and changing the collection at the same time. That is not possible.

You could solve this by using a for-loop (be careful, the length of the loop might change due to the removal of elements)

like image 166
Emond Avatar answered May 04 '26 00:05

Emond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!