2

I have the need to clone all of the contents of a tab to reflect the current state of a WPF TabItem, fully preserving all the bindings. The requirement is that each Tab should function independently with its own group of identical controls. I've so far only managed to create blank tabs. MSDN suggests this isn't possible. Seems like pretty basic functionality for MS to miss, so is this possible?

//    locate the TabControl that the tab will be added to
TabControl itemsTab = (TabControl) this.FindName("tabControl");

//    create and populate the new tab and add it to the tab control
TabItem newTab = new TabItem(); //This should instead clone an existing tab called "mainTab"
newTab.Content = detail;
newTab.Header = name;
itemsTab.Items.Add(newTab);

//    display the new tab to the user; if this line is missing
//    you get a blank tab
itemsTab.SelectedItem = newTab;
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
whoblitz
  • 1,065
  • 1
  • 11
  • 17

2 Answers2

3
 public MainWindow()
    {
        InitializeComponent();
        TabItem tab2 = TrycloneElement(tab1);
        if (tab2 != null)
            main.Items.Add(tab2);
    }




    public static T TrycloneElement<T>(T orig)
    {
        try
        {
            string s = XamlWriter.Save(orig);

            StringReader stringReader = new StringReader(s);

            XmlReader xmlReader = XmlTextReader.Create(stringReader, new XmlReaderSettings());
            XmlReaderSettings sx = new XmlReaderSettings();

            object x = XamlReader.Load(xmlReader);
            return (T)x;
        }
        catch
        {
            return (T)((object)null);
        }

    }

XAML

    <TabControl Width="500" x:Name="main">
        <TabItem Header="AMTAB1" x:Name="tab1">
            <TextBlock Text="blalbla"></TextBlock></TabItem>
    </TabControl>
S3ddi9
  • 2,121
  • 2
  • 20
  • 34
  • Not to sound cynical, but wouldn't this break the bindings of events by having elements with duplicate names? Among things being cloned are a button that fires off an async web request and a datagrid with bound data. – whoblitz Dec 19 '12 at 13:14
  • No as long as you don't use x:FieldModifier="Public" its OK **tried it my self** – S3ddi9 Dec 19 '12 at 13:19
0

Why do you want to clone a full tabpage?

If you have a viewmodel for your data using MVVM separating your ui from data - then you can just make a clone of your data, this is easier and a much cleaner design and you avoid problems with visual tree, parent etc.

So your code could just be something like new Maintab(){DataContext=MainData.Clone()}

Rune Andersen
  • 1,650
  • 12
  • 15