2013-05-05 132 views
2

我在MainWindow.Resources定義以下樣式:全局樣式不工作

<Style TargetType="{x:Type ComboBox}"> 
    <Setter Property="Height" Value="26"/> 
    <Setter Property="ItemTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <TextBlock Text="{Binding}"/> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter> 
    <Setter Property="VerticalContentAlignment" Value="Center"/> 
    <Setter Property="Width" Value="358"/> 
</Style> 
<Style TargetType="{x:Type TextBlock}"> 
    <Setter Property="MaxWidth" Value="350"/> 
    <Setter Property="TextTrimming" Value="CharacterEllipsis"/> 
    <Setter Property="VerticalAlignment" Value="Center"/> 
</Style> 

TextBlock的風格正在爲我的主窗口中定義的TextBlock元素,但它不工作作爲DataTemplate中的TextBlock的我的ComboBoxes。爲什麼?

如果我設置元素本身內部TextBlock的性質,一切工作正常:

<Style TargetType="{x:Type ComboBox}"> 
    <Setter Property="Height" Value="26"/> 
    <Setter Property="ItemTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <TextBlock MaxWidth="350" Text="{Binding}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"/> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter> 
    <Setter Property="VerticalContentAlignment" Value="Center"/> 
    <Setter Property="Width" Value="358"/> 
</Style> 

回答

2

模板有各種各樣的不同的範圍,可以將風格轉向即使在整個應用程序的數據和控制模板中也適用Application.Resources

0

使用動態資源

<DataTemplate DataType="{x:Type local:DataSource}"> 
    <TextBox Style="{DynamicResource TextBoxStyle}" Text="{Binding}" /> 
</DataTemplate> 

<ComboBox> 
    <ComboBox.Resources> 
      <Style x:Key="TextBoxStyle" BasedOn="{StaticResource {x:Type ListBoxItem}}" TargetType="TextBox"> 
     </Style> 
    </ComboBox.Resources> 
</ComboBox>