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

巧了我就是萌 提交于 2019-12-11 12:13:15

问题


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;

回答1:


 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>



回答2:


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



来源:https://stackoverflow.com/questions/13951303/whats-the-easiest-way-to-clone-a-tabitem-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!