Reputation: 1
I need to copy an UIElement
.
I searched for a solution and found this example:
string saved = XamlWriter.Save(canvas1);
StringReader sReader = new StringReader(saved);
XmlReader xReader = XmlReader.Create(sReader);
Canvas newCanvas = (Canvas)XamlReader.Load(xReader);
stackPanel2.Children.Add(newCanvas);
It worked perfectly.
My application copies a long list of UIElement
s and I found that it takes a lot of time.
Does somebody have an idea how to copy UIElement
s faster?
Upvotes: 0
Views: 1504
Reputation: 7152
You can use extension method on UIElement:
static class ExtMethods
{
public static T GetCopy<T>(this T element) where T : UIElement
{
using (var ms = new MemoryStream())
{
XamlWriter.Save(element, ms);
ms.Seek(0, SeekOrigin.Begin);
return (T)XamlReader.Load(ms);
}
}
}
Usage:
Canvas copy = canvas1.GetCopy();
Upvotes: 1