简体   繁体   English

如何快速复制UIElement?

[英]How to copy an UIElement fast?

I need to copy an UIElement . 我需要复制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. 我的应用程序复制了很长的UIElement列表,但我发现这花费了很多时间。 Does somebody have an idea how to copy UIElement s faster? 有人知道如何更快地复制UIElement吗?

You can use extension method on UIElement: 您可以在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();

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

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