2010-11-16 139 views
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); 

我結束了在標籤控制選項卡可見,但它是不可選擇的,我什麼都看不到的它。

回答

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> 

希望這有助於!

相關問題