tags:

views:

44

answers:

2

I've got a tab control, and when the user wants to add to it, then I want to copy a couple of elements that already exist (not just reference them). Now, so far I've just hard-copied the variables I want. But I've come a cropper in the automatic sizing code- that is, the copied element noticeably lags behind the original when resizing the window. In addition, it's just infeasible to keep copying each element that I need to copy as that list grows. Is there some method I can use that will copy a WPF control? Right now, that's just a text box and a tab item.

+2  A: 

I may be miss-understanding your question, but you could create a custom UserControl, and whenever you need to add a new control, just create a new instance of that control and add it to your scene, this way you can use DataContext's to help with the data binding which you can use from the control your copying:

MyControl newControl = new MyControl { DataContext = controlToCopy.DataContext };
myGrid.Children.Add(newControl);

Or similar...

or do you need it to be more dynamic than that?

Mark
Switching the DataContext did the trick. Thanks!
DeadMG
+1  A: 

I can't quite tell what it is you're trying to do but if you want a new instance identical to an existing control instance you can use XamlWriter and XamlReader to serialize/deserialize the control:

MyControl copy = XamlReader.Parse(XamlWriter.Save(controlInstance)) as MyControl;
John Bowen
This is a good solution but will require a lot of customization(in case you use binding, StaticResources, X:Name attributes etc.-So you must take care of issues mentioned in these articles Serialization Limitations of XamlWriter.Save[http://msdn.microsoft.com/en-us/library/ms754193.aspx] Being written by XamlWriter[http://blogs.msdn.com/b/mikehillberg/archive/2006/09/16/xamlwriter.aspx]
akjoshi