1

我正在尝试将选项卡动态添加到选项卡控件。我在资源中有控制模板:

<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);

我最终在选项卡控件中看到了选项卡,但它是不可选择的,我看不到任何东西。

4

1 回答 1

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);
}

用户界面

<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>

希望这可以帮助!

于 2010-11-17T02:02:03.903 回答