Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TabItem Within a ItemsControl

I'm trying to make a TabControl which takes a list and makes a TabItem for each element in that list. I figured making an ItemsControl and then setting the panel to a TabControl would do this but it doesn't seem to work. Is there anyway to make this work?

like image 442
Coat Avatar asked Dec 14 '22 18:12

Coat


1 Answers

There's no need for an ItemsControl. Rather, the TabControl has an ItemsSource property. You can set this to, for example, an IEnumerable<string>, and a TabItem will be created for every item in the enumerable.

For example, in XAML:

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

And when Items is set to List<string> { "a", "b", "c" }, this is produced: enter image description here

However, I'm assuming your main aim wasn't just to create an empty TabItem for every single item in any given enumerable, so in order to actually fill each TabItem, you'll 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 ItemsSource, so it'll be a lot easier to make the items in your ItemsSource objects of your own creation, in which you can make YourText a property. I've created my own TestClass with a YourText property and changed the Items property to an IEnumerable containing two TestClasses. (The first has YourText = "first tab", the second YourText = "second tab".) This is what the TabControl looks like now with the ItemsSource set to the IEnumerable and the ItemsControl.ContentTemplate in place:

enter image description here

This is nearly as basic an example as you can get, but the ControlTemplate can be expanded however you see fit, and most if not all controls can be used in there in the same fashion you'd ordinarily place them in a Window or TabItem.

If you want to alter the header, so it doesn't end up showing your type name, use the TabControl.ItemTemplate property in a similar fashion as the ControlTemplate is 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 one: http://tech.pro/tutorial/1028/wpf-tutorial-binding-to-a-tabcontrol

like image 69
furkle Avatar answered Jan 08 '23 18:01

furkle