Using TabItem inside ItemsControl

I am trying to make a TabControl that takes a list and makes a TabItem for each item in that list. I decided to make an ItemControl and then set the panel to a TabControl, but that doesn't work. Is there a way to make this work?

+3


source to share


1 answer


No need for ItemsControl. Rather, the TabControl has an ItemsSource property. You can set this to for example, IEnumerable<string>

and a TabItem will be created for each item in the enumerable.

For example, in XAML:

<TabControl ItemsSource="{Binding Items}">
</TabControl>

      

And when the elements are set to a value List<string> { "a", "b", "c" }

, this is done: enter image description here

However, I am assuming that your main goal was not only to create an empty TabItem for every single item in any given enumeration, so to actually populate each TabItem you will want to use the TabControl's ContentTemplate property:

<TabControl ItemsSource="{Binding Items}">
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBlock VerticalAlignment="Top" Text="{Binding YourText}"></TextBlock>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

      



Note that the ContentTemplate property takes its DataContext from any given item in the ItemsSource, so it will be much easier to make items in ItemsSource objects of your own creation where you can make the YourText property. I created my own TestClass with YourText property and changed the Items property to IEnumerable containing two TestClasses. (The first has the meaning "Your text" = "first tab", the second is "second tab"). This is what the TabControl now looks like with ItemsSource set to IEnumerable and ItemsControl.ContentTemplate:

enter image description here

This is almost as basic an example as you can get, but the ControlTemplate can be extended as you see fit, and most, if not all of the controls can be used there in the same way that you would normally place them in a window or TabItem.

If you want to change the title so that it doesn't show your type name, use the TabControl.ItemTemplate property in the same way as the ControlTemplate used above.

If you want to know more, kennyzx provided this link: http://tech.pro/tutorial/1028/wpf-tutorial-binding-to-a-tabcontrol

And Panjak Nikam provided this: http://tech.pro/tutorial/1028/wpf-tutorial-binding-to-a-tabcontrol

+6


source







All Articles