无法删除WPF中的子项

本文关键字:WPF 删除 | 更新日期: 2023-09-27 18:26:16

我有一个统一的网格,其中动态添加了矩形。我想删除一个特定的矩形,但在尝试将其传递给remove方法时遇到了以下错误:

无法从"System.Drawing.Rectangle"转换为"System.Windows.UIElement"

我的代码是:

        Rectangle swatch = (Rectangle)ug_Thumbnails.FindName("s_" + _instance);
        ug_Thumbnails.Children.Remove(swatch);

我试着选角,但出现了一个错误,说你做不到。

编辑:根据请求,以下是创建矩形的代码:

        System.Windows.Shapes.Rectangle swatch = new System.Windows.Shapes.Rectangle();
        swatch.Width = 50;
        swatch.Height = 50;
        swatch.Margin = new Thickness(0, 5, 5, 0);
        swatch.StrokeThickness = 1;
        swatch.Stroke = System.Windows.Media.Brushes.Gray;
        swatch.Name = "s_" + name.ToString();
        double groupsize = 100 / colors.Count();
        DrawingBrush blackBrush = new DrawingBrush();
        DrawingGroup checkersDrawingGroup = new DrawingGroup();
        List<SolidColorBrush> brushes = colors;
        double location = 0;
        for (int i = 0; i < colors.Count(); i++)
        {
            GeometryDrawing drawing = new GeometryDrawing(brushes[i], null,
                new RectangleGeometry(new Rect(location, 0, groupsize, groupsize)));
            checkersDrawingGroup.Children.Add(drawing);
            location += groupsize;
        }
        blackBrush.Drawing = checkersDrawingGroup;
        swatch.Fill = blackBrush;
        swatch.MouseUp += new MouseButtonEventHandler(loadSwatchResources);
        ug_Thumbnails.Children.Add(swatch);

无法删除WPF中的子项

在WPF中引用矩形时,需要在System.Windows.Shapes中使用矩形。这是专门针对WPF中的矩形的,因此与System.Drawing矩形类有点不同。您应该能够转换为此版本的矩形,因为它派生自FrameworkElement。看见http://msdn.microsoft.com/en-us/library/system.windows.shapes.rectangle(v=vs.110).aspx获取更多信息。