动态添加选项卡到选项卡控件
问题描述:
我想动态添加选项卡到选项卡控件。我对资源的控制模板:动态添加选项卡到选项卡控件
<ControlTemplate x:Key="memoTab" TargetType="{x:Type TabItem}">
<TabItem Header="Memo">
<TextBox Name="memoText"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AcceptsReturn="True"/>
</TabItem>
</ControlTemplate>
我在代码中创建标签的背后:
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);
我结束了在标签控制选项卡可见,但它是不可选择的,我什么都看不到的它。
答
我能复制它,尝试这种方式来代替:
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>
希望这有助于!