c# - Cloning WPF controls and object hierarchies -


i have problems cloning object hierarchie. it's toolkit modelling applications, toolbox contains class instances prototypes. i'm having hard time cloning these :)

the following code shows problem:

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; }   ... } 

when insert object of acontainingclass project worksheet, should cloned. far tried manual cloning (which fails because of private fields in base classes) , binary serialization (binaryformatter , memorystreams).

the first approach lacks way call base.clone() method (or wrong?), latter not work because uielements aren't [serializable].

note: must deep copy!

any ideas? thanks!


update

just clarify manual cloning approach: if each class has it's own clone method, how call clone method of base class?

public class shape { // not abstract more   ...   public shape clone() {     shape clone = new shape() { propertya = this.propertya, ... };     ...do xamlwriter things clone uielements...     return clone;   } }  public class movableshape : shape {   ...   public movableshape clone() {      // how call base.clone???       // required because have no access private fields!   } } 

if attempting clone uielements, use xamlwriter save string, though no method of cloning foolproof. use xamlreader load copy. still run issues. things handlers not being copied, x:name being duplicated, etc. simple elements grid or brush, works great.

edit 1: there no generic way clone anything, however:

1) if clone function written correctly, call base clone you, , copy base class stuff, too. if isn't written correctly calling base clone won't much, though can call private method this way.

2) if have to, can use reflection copy pretty anything, click handlers, old object new object.

3) xamlwriter , xamlreader copy , instantiate heirarchies of objects, minus properties.

edit 2: here's common cloning design pattern use in class hierarchies. assume base class shape, derived class circle:

protected circle(circle t) {     copyfrom(t); }  public override object clone() {     return new circle(this); }  protected void copyfrom(circle t) {     // ensure have copy not self-reference     if (t == null || object.referenceequals(t, this))         return;      // base     base.copyfrom((shape)t);      // derived     diameter = t.diameter; } 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -