簡體   English   中英

在WPF中克隆TabItem的最簡單方法是什么?

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

我需要克隆選項卡的所有內容以反映WPF TabItem的當前狀態,完全保留所有綁定。 要求是每個Tab應該獨立地使用其自己的相同控件組。 到目前為止,我只設法創建空白標簽。 MSDN建議這是不可能的。 看起來很像MS錯過的基本功能,這可能嗎?

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

為什么要克隆完整的標簽頁?

如果你有一個使用MVVM的數據視圖模型將你的ui與數據分開 - 那么你可以只修復你的數據,這樣更簡單,設計更清晰,你可以避免視覺樹,父等問題。

所以你的代碼可能就像新的Maintab(){DataContext = MainData.Clone()}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM