1

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.

bone_appettit
  • 105
  • 1
  • 6
  • Interacting with controls from C# code in WPF isn't a popular practice (too hard in comparison to XAML). So, don't expect the fast answer. But basically you can't. Only parent can manage children. Child can't manage parent. Then get reference to the parent and interact with it. – aepot Apr 28 '21 at 17:20
  • Instead of sending brd1 as a parameter you should create a new border with the same properties as brd1 and send it. This way you don't have to remove anything since they are two different objects. – Ostas Apr 28 '21 at 19:51

1 Answers1

1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88