C#画布的所有子复制到其他画布 [英] c# copy all the children of canvas to another canvas
问题描述
我试图找到一种方法,一个画布的所有子复制到另一个画布。类型并不重要,因为它有不同类型的孩子。
I am trying to find a way to copy all the children of one canvas to another canvas. Type doesn't matter because it has different types of children.
private void add_template_Click(object sender, RoutedEventArgs e)
{
root.Children.Clear();
foreach(var c in Template_canvas1.Children)
{
root.Children.Add(c);
}
}
以上代码给出了一个错误无效的操作错误。
我想从template_canvas1复制的孩子根本画布。建议?
Above code gives an error "Invalid operation error". I want to copy children from template_canvas1 to root canvas. Suggestions?
推荐答案
的问题是,一个的UIElement
只能属于以一次一个家长。为了增加您的物品进入根
画布,你需要首先从 Template_canvas1
画布删除它们。
The problem is, that a UIElement
can only belong to one parent at a time. In order to add your items into the root
canvas, you need to first remove them from the Template_canvas1
canvas.
请参阅下面的代码。我创建的数组 UI元素
复制,然后把它们添加到<$ C $之前,从 Template_canvas1
删除C>根。
See the following code. I create an array of the UIElements
to copy, and then remove them from Template_canvas1
before adding them to root
.
private void add_template_Click(object sender, RoutedEventArgs e)
{
var childrenList = Template_canvas1.Children.Cast<UIElement>().ToArray();
root.Children.Clear();
foreach (var c in childrenList)
{
Template_canvas1.Children.Remove(c);
root.Children.Add(c);
}
}
还有一个选择,如果你不这样做要从中删除 Template_canvas1
的项目,你可以创建UI元素的深层复制。另请参见下面的,我不会从 Template_canvas1
删除的项目:
There is one more option, if you don't want to remove the items from Template_canvas1
, you can create a Deep Copy of the UIElements. See also the following where I do not remove the items from Template_canvas1
:
private void add_template_Click(object sender, RoutedEventArgs e)
{
root.Children.Clear();
foreach (UIElement child in Template_canvas1.Children)
{
var xaml = System.Windows.Markup.XamlWriter.Save(child);
var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
root.Children.Add(deepCopy);
}
}
这篇关于C#画布的所有子复制到其他画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!