如何克隆WPF对象?

时间:2008-08-28 15:14:30

标签: c# wpf binding clone

任何人都有一个很好的例子,如何深度克隆WPF对象,保留数据绑定?


标记答案是第一部分。

第二部分是你必须创建一个ExpressionConverter并将其注入序列化过程。详细信息如下:
http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571

4 个答案:

答案 0 :(得分:58)

我做过的最简单的方法是使用XamlWriter将WPF对象保存为字符串。 Save方法将序列化逻辑树中的对象及其所有子对象。现在,您可以创建一个新对象并使用XamlReader加载它。

例如: 将对象写入xaml(假设该对象是Grid控件):

string gridXaml = XamlWriter.Save(myGrid);

将其加载到新对象中:

StringReader stringReader = new StringReader(gridXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
Grid newGrid = (Grid)XamlReader.Load(xmlReader);

答案 1 :(得分:33)

在.NET 4.0中,新的xaml序列化堆栈使这个过程变得更容易。

var sb = new StringBuilder();
var writer = XmlWriter.Create(sb, new XmlWriterSettings
{
    Indent = true,
    ConformanceLevel = ConformanceLevel.Fragment,
    OmitXmlDeclaration = true,
    NamespaceHandling = NamespaceHandling.OmitDuplicates, 
});
var mgr = new XamlDesignerSerializationManager(writer);

// HERE BE MAGIC!!!
mgr.XamlWriterMode = XamlWriterMode.Expression;
// THERE WERE MAGIC!!!

System.Windows.Markup.XamlWriter.Save(this, mgr);
return sb.ToString();

答案 2 :(得分:4)

这里有一些很棒的答案。很有帮助。我曾尝试过各种复制绑定信息的方法,包括http://pjlcon.wordpress.com/2011/01/14/change-a-wpf-binding-from-sync-to-async-programatically/中概述的方法,但这里的信息是互联网上最好的!

我创建了一个可重用的扩展方法来处理InvalidOperationException“绑定在使用后无法更改。”在我的场景中,我维护了一些人编写的代码,并且在主要的DevExpress DXGrid框架升级后,它没有工作时间更长以下完美解决了我的问题。我返回对象的代码部分可能更好,我稍后会重新考虑它。

/// <summary>
/// Extension methods for the WPF Binding class.
/// </summary>
public static class BindingExtensions
{
    public static BindingBase CloneViaXamlSerialization(this BindingBase binding)
    {
        var sb = new StringBuilder();
        var writer = XmlWriter.Create(sb, new XmlWriterSettings
        {
            Indent = true,
            ConformanceLevel = ConformanceLevel.Fragment,
            OmitXmlDeclaration = true,
            NamespaceHandling = NamespaceHandling.OmitDuplicates,
        });
        var mgr = new XamlDesignerSerializationManager(writer);

        // HERE BE MAGIC!!!
        mgr.XamlWriterMode = XamlWriterMode.Expression;
        // THERE WERE MAGIC!!!

        System.Windows.Markup.XamlWriter.Save(binding, mgr);
        StringReader stringReader = new StringReader(sb.ToString());
        XmlReader xmlReader = XmlReader.Create(stringReader);
        object newBinding = (object)XamlReader.Load(xmlReader);
        if (newBinding == null)
        {
            throw new ArgumentNullException("Binding could not be cloned via Xaml Serialization Stack.");
        }

        if (newBinding is Binding)
        {
            return (Binding)newBinding;
        }
        else if (newBinding is MultiBinding)
        {
            return (MultiBinding)newBinding;
        }
        else if (newBinding is PriorityBinding)
        {
            return (PriorityBinding)newBinding;
        }
        else
        {
            throw new InvalidOperationException("Binding could not be cast.");
        }
    }
}

答案 3 :(得分:-1)

怎么样:

    public static T DeepClone<T>(T from)
    {
        using (MemoryStream s = new MemoryStream())
        {
            BinaryFormatter f = new BinaryFormatter();
            f.Serialize(s, from);
            s.Position = 0;
            object clone = f.Deserialize(s);

            return (T)clone;
        }
    }

当然这会深深地克隆任何物体,它可能不是城里最快的解决方案,但它维护得最少... :)