简体   繁体   English

如何从 UIElement 中删除父级? WPF

[英]How to remove a parent from UIElement? WPF

I have some grid with border (grid name is "maingrid")我有一些带边框的网格(网格名称是“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")然后我有另一个带有构造函数和网格的 window(网格名称是“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" ?如何从“brd2”中删除父母并使此边框成为“somegrid”的子元素,但我需要将“brd1”与“maingrid”一起保留
In short, I need to clone "brd1" with null parent property.简而言之,我需要使用 null 父属性克隆“brd1”。

You cannot reuse the same Border element in two places as an element can only appear once in the visual tree.您不能在两个地方重复使用相同的Border元素,因为一个元素只能在可视化树中出现一次

You should clone the element into a new instance.您应该将该元素克隆到一个新实例中。 One way to do this is to use the XamlWriter class:一种方法是使用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.当然,您也可以选择克隆元素,只需使用new属性创建它的新实例并以通常的方式设置其所有属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM