2013-05-05 73 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>