全局风格不起作用

本文关键字:不起作用 风格 全局 | 更新日期: 2023-09-27 18:12:24

我在主窗口中定义了以下样式。资源:

<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元素定义在我的主窗口,但它不工作的TextBlock用作DataTemplate为我的组合框。为什么?

如果我在元素内部设置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>

全局风格不起作用

模板有不同的排序范围,您可以将样式移动到Application.Resources,甚至在整个应用程序中的数据和控制模板中也适用。

使用动态资源

 <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>