添加动态的TabItems [英] Adding TabItems dynamically

查看:126
本文介绍了添加动态的TabItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的TabControl 控制

<TabControl DockPanel.Dock="Left" Name="Farms_myVillages"
            ItemsSource="{Binding Villages}">
</TabControl/>

在后面我加了一些标签动态的代码的TabControl 如下:

In the code behind I added some tabs dynamically to the TabControl as follows:

foreach (Village vill in Villages)
{
    TabItem tab = new TabItem();
    tab.Header = vill.Name;
    VillageUserControl c = new VillageUserControl();
    c.DataContext = vill;
    tab.Content = c;
    Farms_myVillages.Items.Add(tab);
}

其中VillageUserControl是与指定的村
这样处理一个用户控件代码工作正常,并执行了预期的效果...

where VillageUserControl is a UserControl that deal with the specified village This code works fine and it executes the expected results...

的问题是,我不希望这是在后面的代码,但只是在XAML本身。
我想这一点:

The problem is that I don't want this to be in the code behind but just in the xaml itself. I tried this:

<TabControl DockPanel.Dock="Left" Name="Farms_myVillages"
            ItemsSource="{Binding Villages}">
      <TabControl.ItemContainerStyle>
          <Style TargetType="TabItem">
              <Setter Property="Header" Value="{Binding Name}"/>
              <Setter Property="Content">
                 <Setter.Value>
                    <u:VillageUserControl DataContext="{Binding}"/>
                 </Setter.Value>
              </Setter>
          </Style>
      </TabControl.ItemContainerStyle>
</TabControl>



我运行后,它抛出一个异常:指定的元素已经是另一个元素的逻辑子。首先断开了。

after I run, it throws an exception: "Specified element is already the logical child of another element. Disconnect it first."

所以我错过了什么,请帮助我在这里...

so did I miss something, please help me here...

推荐答案

您设置了错误的东西,你不应该修改的 ItemContainerStyle 不过的 TabControl.ItemTemplate 以页眉和 TabControl.ContentTemplate 的内容。

You set the wrong thing, you should not modify the ItemContainerStyle but the TabControl.ItemTemplate for the header and TabControl.ContentTemplate for the content.

(唯一的例外可能与事实做在风格只有一个 VillageUserControl 被创建,但风格适用于多个标签的项目。)

(The exception may have to do with the fact that in the style only one VillageUserControl is created, but the style applies to multiple tab items.)

这篇关于添加动态的TabItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆