简体   繁体   中英

What's the easiest way to clone a TabItem in WPF?

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

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()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM