【问题标题】:What's the easiest way to clone a TabItem in WPF?在 WPF 中克隆 TabItem 的最简单方法是什么?
【发布时间】:2012-12-06 17:47:33
【问题描述】:

我需要克隆选项卡的所有内容以反映 WPF TabItem 的当前状态,完全保留所有绑定。要求是每个选项卡都应使用自己的一组相同控件独立运行。到目前为止,我只设法创建了空白标签。 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;

【问题讨论】:

  • 获取 Xaml 然后将其保存到新的 TabItem

标签: c# .net wpf tabcontrol tabitem


【解决方案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>

【讨论】:

  • 听起来不是很愤世嫉俗,但这不会因为元素具有重复名称而破坏事件绑定吗?被克隆的东西包括一个触发异步 Web 请求的按钮和一个带有绑定数据的数据网格。
  • 没有,只要你不使用 x:FieldModifier="Public" 就可以了我自己试过
【解决方案2】:

为什么要克隆一个完整的标签页?

如果您有一个使用 MVVM 将您的 ui 与数据分开的数据视图模型 - 那么您可以克隆您的数据,这更容易且设计更简洁,并且您可以避免可视化树、父级等问题。

所以您的代码可能只是类似于 new Maintab(){DataContext=MainData.Clone()}

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 2010-11-19
    • 2021-06-29
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多