How to remove a parent from UIElement? WPF

406 Views Asked by At

I have some grid with border (grid name is "maingrid")

Border brd1 = new Border();
this.maingrid.Children.Add(brd1);
SomeClass = new SomeClass(brd1);

Then I have another window with a constructor and with grid too (grid name is "somegrid")

public SomeClass(Border brd2)
{
InitializeComponent();

//i tried to do that: ((Grid)brd2.Parent).Children.Remove(brd2)
//but if i do that, border from "maingrid" removes too
this.somegrid.Children.Add(brd2);
}

How can I remove parents from "brd2" and make this border a child element for "somegrid", but i need to keep "brd1" with "maingrid"?
In short, I need to clone "brd1" with null parent property.

1

There are 1 best solutions below

0
On BEST ANSWER

You cannot reuse the same Border element in two places as an element can only appear once in the visual tree.

You should clone the element into a new instance. One way to do this is to use the XamlWriter class:

private static T Clone<T>(T element)
{
    string xaml = XamlWriter.Save(element);
    using (StringReader stringReader = new StringReader(xaml))
    using (XmlReader xmlReader = XmlReader.Create(stringReader))
        return (T)XamlReader.Load(xmlReader);
}

Usage:

Border brd2 = Clone(brd1);

You may of course also choose to clone the element by simply creating a new instance of it using the new properties and set all of its properties the usual way.