【问题标题】:How to set the header of a TabItem when using ItemsSource使用 ItemsSource 时如何设置 TabItem 的标题
【发布时间】:2012-12-06 09:27:29
【问题描述】:

将用户控件集合绑定到 TabControl 的 ItemsSource 属性很有用。

然而,一旦你走这条路,似乎很难从代码中设置每个 tabitem 的标题。 我可以从 xaml 中做到这一点但我需要从代码中做到这一点

所以我正在寻找的是类似的东西

TabControl tabControl = new TabControl();

tabControl.ItemsSource = collectionOfUserControls;

tabControl.HeaderPath = "Title" // this property is not available

编辑

如果手动添加到集合中,这是如何做到的。问题是在使用 ItemsSource 属性时如何设置标题。

        var vragenlijsten = new UserControl[]
                                {
                                    new UC1() ,
                                    new UC2(), 
                                };


        TabControl tabControl = new TabControl();

        foreach (var vragenlijst in vragenlijsten)
        {
            var tabItem = new TabItem();
            tabItem.Content = vragenlijst;
            tabItem.Header = vragenlijst.GetType();
            tabControl.Items.Add(tabItem);
        }

【问题讨论】:

  • 为什么你需要从代码中做到这一点?也有一个 HeaderTemplate..
  • 我想知道如何在代码中做到这一点:) 如果它不可行/不实用,那也是知识
  • 当您带着“传统”思维并尝试在 WPF 中使用它时,没有什么是实用的。实际上,我将 TabControl 视为 ViewModel 的 IEnumerable,然后将它们与各自的视图一起呈现在屏幕上。这就是 WPF 的思维方式。

标签: wpf xaml


【解决方案1】:

如果您必须在代码中执行此操作,则需要检索 TabItems 并为每个设置标头。像这样的:

(tabControl.Items[0] as TabItem).Header = "Title";

【讨论】:

  • 听起来很合理,但你试过吗?如果你使用 ItemsSource 来绑定你会发现投出的 Items 集合中的 item 不是 TabItem。
  • 我试过了。我的回答假设您的collectionOfUserControlsTabItems 的集合。如果您有更多不是 TabItems 的控件(尽管我不知道您为什么会这样做),您可以在之前添加一个检查,例如:if(tabControl.Items[0] is TabItem)
猜你喜欢
  • 2014-11-08
  • 1970-01-01
  • 2011-01-24
  • 2012-11-13
  • 2020-06-13
  • 1970-01-01
  • 2011-09-10
  • 2021-09-11
  • 2015-01-31
相关资源
最近更新 更多