简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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