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?
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:
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With