问题
I have a style created in my windows resources area:
<Style TargetType="TextBlock">
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
</Style>
I thought this meant that all text blocks would have this style, so when I create my list view column:
<GridViewColumn>
<GridViewColumnHeader Content="Source"/>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Source, Mode=OneWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
The ellipsis style is NOT applied to the text block in the column.
If I name the style with x:Key, then use Style={StaticResource xxx} then it works - why doesn't the unnamed approach work?
Here's the complete window XAML:
<Window x:Class="ListViewStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
</Style>
</Window.Resources>
<ListView ItemsSource="{Binding Rows}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumnHeader Content="Source"/>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Source, Mode=OneWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumnHeader Content="Primary"/>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Primary, Mode=OneWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumnHeader Content="Secondary"/>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Secondary, Mode=OneWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Window>
回答1:
You may be defining another TextBlock
style, closer to the TextBlock
itself.
The way WPF searches for a style starts with the item to be styled. If it sets the Style
property, then it uses that. Otherwise, it checks the parent's resources, then its grandparent's resources, and so on, using the first style it finds. If it doesn't find a style in your application it uses the default style.
There is probably a TextBlock
style in one of the TextBlock
's ancestors. If it finds a style there, it won't use the one at the window level.
You can specify that one style is based on another, with the BasedOn property.
来源:https://stackoverflow.com/questions/10231095/why-doesnt-my-text-block-style-get-applied