2010-06-25 21 views
4

對於WPF而言並不新鮮,並且具有Tabs,並且在每個選項卡中內容呈現在彎曲的角落面板/窗口/ whateveryouwannacallit中。我不知道如何做到這一點(Style,ControlTemplate),但決定採用DataTemplate方式。在內容中設置的WPF DataTemplate屬性

所以現在我有這樣的DataTemplate:

<DataTemplate x:Key="TabContentPresenter" > 
    <Border Margin="10" 
      BorderBrush="{StaticResource DarkColorBrush}" 
      CornerRadius="8" 
      BorderThickness="2" 
      Grid.Row="0" 
      Padding="5" 
      Background="{TemplateBinding Background}">   

     <ContentPresenter Content="{Binding}" /> 

    </Border> 
</DataTemplate> 

正如你可以與背景屬性我wan't設置在內容的背景顏色,但不知道怎麼看。我在這裏使用它。

<Grid> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="120"/> 
       <RowDefinition Height="*" /> 
      </Grid.RowDefinitions> 

      <ContentControl ContentTemplate="{StaticResource TabContentPresenter}" Background="White"> 


       <!-- Something Here --> 

      </ContentControl> 

      <ContentControl ContentTemplate="{StaticResource TabContentPresenter}" Grid.Row="1" Background="Blue"> 

       <!-- Something Here --> 

      </ContentControl> 

     </Grid> 

是否在這裏使用DataTemplate錯誤還是有其他方法嗎?

我可以直接在內容上設置背景,並從模板中的填充更改爲內容中的邊距,但在某些類似的情況下不起作用,只需設置一次即可。

編輯:

按照建議我改的ControlTemplate,並把它放在裏面的風格。這解決了背景問題,但創建了一個更大的問題。現在內容不會出現。我在博客here上看到,把targetType解決這個問題,但它並沒有解決我的問題。代碼現在看起來像這樣,也改變了ContentControl使用樣式而不是Template。

<Style x:Key="TabContentPresenter" TargetType="ContentControl" > 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ContentControl"> 
       <Border Margin="10" 
      BorderBrush="{StaticResource DarkColorBrush}" 
      CornerRadius="8" 
      BorderThickness="2" 
      Grid.Row="0" 
      Background="{TemplateBinding Background}"> 

        <ContentPresenter Content="{Binding}" /> 

       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

回答

6

使用控件模板代替的DataTemplate

<ControlTemplate x:Key="TabContentPresenter"> 
     <Border Margin="10" 
        CornerRadius="8" 
        BorderThickness="2" 
        Grid.Row="0" 
        Padding="5" 
        Background="{TemplateBinding Background}"> 
      <ContentPresenter Content="{Binding}"/> 
     </Border> 
    </ControlTemplate> 

使用模板代替的ContentTemplate

<ContentControl Background="Green" Template="{StaticResource TabContentPresenter}"/> 
+0

這適用於背景,但現在我的內容不會出現在邊框內。 – 2010-06-25 16:33:54

+2

最後發現,必須將ContentPresenter內容屬性更改爲{TemplateBinding Content}。 – 2010-06-28 16:49:40

5

可能是因爲TemplateBinding不適用於DataTemplate。 Check this question for details

即使它工作,您只需要一個ControlTemplate而不是數據模板。

+0

謝謝,我確實知道,TemplateBinding沒有工作,我把它放在那裏,以顯示我想要的東西。我真的不知道DataTemplate和ControlTemplate之間的區別,所以我從來不知道使用哪一個。 – 2010-06-25 16:29:38

+0

第一個鏈接已損壞。 – Deantwo 2017-09-15 12:28:14