2013-10-03 19 views
4

我有以下XAML(簡化):爲什麼Listbox DataTemplate不使用Windows.Resources樣式?

<Window ... 

    <Window.Resources> 
     <Style TargetType="{x:Type TextBlock}" > 
      <Setter Property="FontSize" Value="28" /> 
      <Setter Property="Margin" Value="3" /> 
      <Setter Property="Foreground" Value="Green" /> 
     </Style> 
    </Window.Resources> 

    <StackPanel> 

     <ListBox ItemsSource=... 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal" > 
         <TextBlock Text="{Binding Index}" /> 
         <TextBlock Text="-" /> 
         <TextBlock Text="{Binding Hours, StringFormat={}{0:00}}" /> 
         <TextBlock Text=":" /> 
         <TextBlock Text="{Binding Minutes, StringFormat={}{0:00}}" /> 
         <TextBlock Text=":" /> 
         <TextBlock Text="{Binding Seconds, StringFormat={}{0:00}}" /> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

     ... 

有了這個代碼在Window.Resources定義的樣式沒有被施加到所述的DataTemplate內部TextBlock的,但它是對窗口其他的TextBlocks。

如果我複製樣式,並將其設置在DataTemplate中資源是這樣的:

 <DataTemplate.Resources> 
      <Style TargetType="{x:Type TextBlock}" > 
       <Setter Property="FontSize" Value="28" /> 
       <Setter Property="Margin" Value="3" /> 
       <Setter Property="Foreground" Value="Green" /> 
      </Style> 
     </DataTemplate.Resources> 

然後,它的工作原理。任何想法爲什麼我需要重複風格?

在此先感謝。

回答

3

這是一個WPF怪癖。當控件不是從Control繼承,而是直接從FrameworkElement繼承時,模板內的隱式樣式查找會直接跳到應用程序資源。如果您將樣式放在應用程序資源(App.xaml)中,它將起作用。

或者,你可以使用一個命名的資源和BasedOn引用它:

<DataTemplate.Resources> 
     <Style TargetType="TextBlock" BasedOn="{StaticResource MyTextStyle}" /> 
    </DataTemplate.Resources> 
4

Styles將模板只適用於從System.Windows.Controls.Control繼承的類型和自TextBlock直接從System.Windows.FrameworkElement它不會繼承工作。你必須要麼放棄自己的風格x:Key並明確使用或Application.Resources聲明你的風格,但隨後將適用於所有TextBlocks和我的意思基本上是文本的每一個顯示位,在整個應用程序

+0

這是不正確的。隱式樣式只需要重寫'TextBlock'所具有的'DefaultStyleKey'屬性。 –

+0

重寫'DefaultStyleKey'並在'Window'中編寫隱式樣式有些不同。基本上,當風格評估爲非'System.Windows.Controls.Control'元素時,它不會超越該模板來檢查其他元素資源,而是直接轉到Application.Resources然後是DefaultStyleKey。 – dkozl

+0

你是對的,我沒有注意到你寫道,它只在模板內是真實的。對不起:) –

2

請看看DataTemplate and Style Confusion

我在2006年10月

登載作爲連接「錯誤」 ......

「這種行爲是‘通過設計’,這就是爲什麼模板被視爲一個。封裝邊界。這些模板生成的元素屬於這個範圍。查找具有匹配的TargetType的樣式將停在此邊界。因此,通過模板生成的repro中的TextBlock不會提取相關的Style。而在模板外部定義的TextBlock確實如此。

解決此問題的一種方法是給樣式一個明確的名稱,並在模板中的TextBlock上通過此名稱引用樣式。

相關問題