Search code examples
c#visual-studio-2010xamltabcontroldeep-copy

TabControl Deep Copy


I need to make a deep copy of a tabcontrol.

The large picture is this: I have a project which has a 300 line XAML code TabControl with 8 tabs in it which are pretty big. I also have a TreeView with different items.

When an item in that list is selected it shows the TabControl associated with it. The problem now comes that when I add an element I want to make a deep copy of the original TabControl and associate that new one to the new element (of course I'm going to erase the content in the new one). Shallow copies won't work because they are pointing to the same location in memory, so "=",IClonable are a no go. And the frustrating part is that I can't use deep copy with serialization because the TabControl is not serializable. And I can't (or should say won't) make a custom TabControl which is serializable because the TabControl is 300 line in XAML and it would be 600 line in code so it's a waste of space and time.

I've searched for this for 2 days and didn't find anything. There is no need for me to show the code because I'm looking for a general purpose Deep Copy method that can copy any type of a TabControl.


Solution

  • After searching some more I initially tried a different way but it turned out to be more trouble than it's worth (tried with data binding and working more in code but still to much).

    So the solution is to use XamlReader and XamlWriter. Official documentation is found here and respectively here !

    To answer my question in code it would be: Say you had this tabcontrol in XAML here:

    <TabControl>
      <TabItem><!--A lot of stuff here--></TabItem>
      <TabItem><!--More stuff here--></TabItem>
    </TabControl>
    

    And remember this is if you have a lot of stuff (basically I didn't mention this but I'm making an interface that creates a pretty complex XML so in that TabControl I'm handling a lot of user generated data)! If you have a simple TabControl just make a custom one in code or simply use DataBindings.

    So the code in the background for making a Deep Copy of that XAML defined TabControl would be this:

    string savedTabControl = XamlWriter.Save(originalTabControl);
    
    StringReader stringReader = new StringReader(savedTabControl);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    TabControl newTabControl = (TabControl)XamlReader.Load(xmlReader);
    

    So this is basically serialization made on xaml controls and not on data.