无法在WPF中删除子项

时间:2014-10-13 01:43:16

标签: c# wpf

我有一个统一的网格,动态添加了矩形。我想删除一个特定的矩形,但在尝试将其传递给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);

1 个答案:

答案 0 :(得分:2)

尝试在WPF中引用矩形时,需要在System.Windows.Shapes中使用Rectangle。这特别适用于WPF中的矩形,因此与System.Drawing矩形类略有不同。您应该能够转换为此版本的矩形,因为它派生自FrameworkElement。有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.windows.shapes.rectangle(v=vs.110).aspx