我在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样式适用于在我的MainWindow中定义的TextBlock元素,但它不适用于我的ComboBoxes用作DataTemplate的TextBlock。为什么呢?
如果我在元素本身内设置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>
答案 0 :(得分:2)
模板具有不同的排序范围,您可以将样式移动到Application.Resources
,即使在整个应用程序的数据和控件模板中也适用。{/ p>
答案 1 :(得分: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>