2011-08-23 140 views
1

我正在編寫一個應用程序,我在其中使用一個選項卡控件,該控件將以打開的一個選項卡開始,但允許用戶打開多個其他選項卡。WPF項目模板 - TabControl

每個打開的選項卡都應該有一個樹形視圖,其中當用戶加載文件時,我使用數據綁定填充該樹形視圖。

我是WPF的新手,但我覺得好像有一種方法可以創建一個包含TabItems應包含的每個元素的模板。我怎樣才能使用模板做到這一點?現在我的標籤項目WPF是以下

<TabItem Header="Survey 1"> 
     <TreeView Height="461" Name="treeView1" VerticalAlignment="Top" 
        Width="625" Margin="0,0,6,0" ItemTemplateSelector="{StaticResource TreeviewDataSelector}" /> 
</TabItem> 

回答

3

我想你想是這樣的:

<Window x:Class="TestWpfApplication.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
<Window.Resources> 
    <DataTemplate x:Key="TabItemTemplate"> 
     <TreeView Height="461" Name="treeView1" VerticalAlignment="Top" 
        Width="625" Margin="0,0,6,0" ItemTemplateSelector="{StaticResource TreeviewDataSelector}" /> 
    </DataTemplate> 

</Window.Resources> 
<Grid> 
    <TabControl ItemsSource="{Binding ListThatPowersTheTabs}" 
       ItemTemplate="{StaticResource TabItemTemplate}"> 
    </TabControl> 
</Grid> 

你基本上創建可重用的模板,因爲你提到的靜態資源以他們的名字命名。

2

通常在這種情況下,我將我的TabControl.ItemsSource綁定到ObservableCollect<ViewModelBase> OpenTabs,所以我的ViewModel負責根據需要添加/刪除新的選項卡。

然後如果你想在每一個標籤的東西,然後覆蓋TabControl.ItemTemplate並使用以下行來指定在哪裏顯示當前選擇的TabItem

<ContentControl Content="{Binding }" />

如果您不需要設置在東西每個選項卡都不需要覆蓋TabControl.ItemTemplate - 它將默認在選項卡中顯示當前選中的ViewModelBase

而且我用的DataTemplates來指定要使用的查看

<DataTemplate TargetType="{x:Type local:TabAViewModel}"> 
    <local:TabAView /> 
</DataTemplate> 

<DataTemplate TargetType="{x:Type local:TabBViewModel}"> 
    <local:TabBView /> 
</DataTemplate> 

<DataTemplate TargetType="{x:Type local:TabCViewModel}"> 
    <local:TabCView /> 
</DataTemplate>