c# - 克隆 WPF 控件和对象层次结构

标签 c# wpf clone deep-copy

我在克隆对象层次结构时遇到了一些问题。它是一个用于建模应用程序的工具包,该工具箱包含作为原型(prototype)的类实例。但是我很难克隆这些 :)

以下代码显示了问题:

public abstract class Shape {
  protected List<UIElement> elements;
  private Canvas canvas;
  ...
  public Canvas getCanvas() { ... };
}

public class MovableShape : Shape {
  protected ... propertyA;
  private ... propertyXY;
  ...
}

public abstract class AbstractLayout : MovableShape, ... {
  ...
}

public class SomeLayoutClass : AbstractLayout, ... {
  ...
}

public class AContainingClass {
  SomeLayoutClass Layout { get; set; }
  ...
}

当我将 AContainingClass 的对象插入到我的项目工作表中时,它应该被克隆。到目前为止,我尝试了手动克隆(由于基类中的 private 字段而失败)和二进制序列化(BinaryFormatterMemoryStreams)。

第一种方法缺少调用 base.clone() 方法的方法(或者我错了吗?),后者不起作用,因为 UIElement 不是t [可序列化]

注意:必须是深拷贝!

有什么想法吗?谢谢!


更新

只是为了阐明我的手动克隆方法: 如果每个类都有自己的Clone方法,如何调用基类的Clone方法?

public class Shape { // not abstract any more
  ...
  public Shape Clone() {
    Shape clone = new Shape() { PropertyA = this.PropertyA, ... };
    ...do some XamlWriter things to clone UIElements...
    return clone;
  }
}

public class MovableShape : Shape {
  ...
  public MovableShape Clone() {
     // how to call base.Clone??? 
     // this would be required because I have no access to the private fields!
  }
}

最佳答案

这里是它的函数:

    public T XamlClone<T>(T source)
    {
        string savedObject = System.Windows.Markup.XamlWriter.Save(source);

        // Load the XamlObject
        StringReader stringReader = new StringReader(savedObject);
        System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
        T target = (T)System.Windows.Markup.XamlReader.Load(xmlReader);

        return target;
    }

关于c# - 克隆 WPF 控件和对象层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6766787/

相关文章:

.net - 是什么让 MVVM 特别适合 WPF?

wpf - 超链接可以在 WPF 控件中显示的 XPS 文件中使用吗?

java - 克隆如何比对象创建具有更高的性能

git - Git : Repository, fork, branch, clone, track 这些词是什么意思?

javascript - 将原始数组与深度克隆进行比较,不起作用

c# - 当我尝试删除导致IOException的文件时,哪个进程正在访问它?

c# - 将隐藏属性设置为列表框项 - C#

c# - 更新网站上文本的最佳方法

c# - 将 UITableView 从列表切换到分组的最佳方法是什么?

wpf - TimeSpan 的 MultiBinding StringFormat