yonit
yonit

Reputation: 1

How to copy an UIElement fast?

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 UIElements and I found that it takes a lot of time. Does somebody have an idea how to copy UIElements faster?

Upvotes: 0

Views: 1504

Answers (1)

JohnyL
JohnyL

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

Related Questions