Adding TabItems dynamically
Solution 1
You set the wrong thing, you should not modify the ItemContainerStyle
but the TabControl.ItemTemplate
for the header and TabControl.ContentTemplate
for the content.
(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.)
Solution 2
Now it is working:
<TabControl Name="Farms_myVillages"
ItemsSource="{Binding Villages}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<u:VillageResources/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
Solution 3
Your approach of not having this in code behind is right, instead of using ItemContainerStyle
use ItemTemplate
and ContentTemplate
. You can have a look at this sample from Josh Smith for creating a tabs using Templates and Styles -
http://code.msdn.microsoft.com/mag200902MVVM/Release/ProjectReleases.aspx?ReleaseId=2026
Related videos on Youtube
Sami Abdelgadir Mohammed
Updated on May 16, 2022Comments
-
Sami Abdelgadir Mohammed about 2 years
I have a
TabControl
control<TabControl Name="Farms_myVillages" ItemsSource="{Binding Villages}"> </TabControl/>
In the code behind I add 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); }
where
VillageUserControl
is aUserControl
that deal with the specified village. This code works fine and it gets the expected results...The problem is that I don't want this to be in the code behind but just in the
xaml
itself.I try this:
<TabControl 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, it throws an exception: "Specified element is already the logical child of another element. Disconnect it first."
Did I miss something? Please help me here...
-
H.B. over 13 yearsYou're welcome, glad it helped :) (On a side note: You can mark answers via the checkmark outline that appears if you move your mouse below the votes on the left, so far you have not accepted any answers to your questions, you might want to go through them and accept the answer that helped the most)