Reputation: 11
I am trying to dynamically add tabs to tab control. I have control template in resources:
<ControlTemplate x:Key="memoTab" TargetType="{x:Type TabItem}">
<TabItem Header="Memo">
<TextBox Name="memoText"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AcceptsReturn="True"/>
</TabItem>
</ControlTemplate>
I create tab in code behind:
TabItem tab = new TabItem();
tab.Template = (ControlTemplate) FindResource("memoTab");
tab.ApplyTemplate();
TextBox tb = (TextBox) tab.Template.FindName("memoText", tab);
tb.DataContext = memo; //this is a string created by linq query
tabControl.Items.Add(tab);
I end up with tab visible in tab control, but it is not selectable, and I cannot see anything in it.
Upvotes: 1
Views: 3502
Reputation: 2837
I could reproduce it, try this way instead:
private void Button_Click(object sender, RoutedEventArgs e)
{
var content = new TextBlock();
content.Text = "Hello World! " + new Random().Next(1, 20).ToString();
TabItem tab = new TabItem();
tab.Header = "Hello world!";
tab.Content = content;
tabControl.Items.Add(tab);
}
UI
<Grid>
<TabControl Name="tabControl">
<TabItem Header="Existing tab 1" />
<TabItem Header="Existing tab 2" />
</TabControl>
<Button HorizontalAlignment="Left" VerticalAlignment="Bottom" Content="Add Tab" Width="100" Height="30" Click="Button_Click" />
</Grid>
Hope this helps!
Upvotes: 1