我正在尝试向制表符控件动态添加标签。我在资源中有控制模板:
<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);
我最终在标签控件中显示了标签,但它无法选择,我看不到任何内容。
答案 0 :(得分:1)
我可以重现它,尝试这样:
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>
希望这有帮助!