wpf - 删除wpf中的矩形/元素

标签 wpf shapes inkcanvas

我在 WPF 中绘制 SQUARE 和其他形状。就这样,

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

我可以用它删除随机行

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!!?
                }
            }
    }

我可以删除随机线,但我不能删除形状

我该怎么办?

最佳答案

您正在对元素集合使用 foreach 循环,同时更改集合。这是不可能的。

你可以通过使用 for 循环来解决这个问题(注意,循环的长度可能会因为删除元素而改变)

关于wpf - 删除wpf中的矩形/元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841450/

相关文章:

wpf - 在 WPF 中使用 UWP 控件

.net - 如何在旋转后而不是之前调整 WPF 元素的大小?

c++ - C++ 中的 2D 形状匹配

c# - 从自己的后台线程更新绑定(bind)控件

python - 为什么我的 Pandas 数据框选择的形状是错误的

.net - 如何使用 WPF 构建一个简单的形状图表应用程序?

c# - 如何删除通用 Windows 平台 (Windows 10) 应用程序中的 InkCanvas 笔画?

wpf - 如何使用代码向 inkcanvas 添加文本?

c# - 在后面的 UserControl 代码中获取依赖属性值

c# - 如何向 ICommand 对象添加键盘快捷键