Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: TextTrimming on a ContentPresenter

Is there a simple way to just get TextTrimming to work with a ContentPresenter?

I have implict styles for TextBlock and AccessText that have TextTrimming set to CharacterEllipsis, but it's not picked up by the ContentPresenter. I can change the ContentPresenter to an AccessText or TextBlock and set it there, but then the template only handles text content.

Any suggestions?

Thanks!

like image 631
dex3703 Avatar asked Apr 27 '11 21:04

dex3703


2 Answers

Implicit Styles for elements that derive from UIElement, but not Control, are not applied if the element is defined in a control's Template unless the implict Style is defined in the application Resources. The same holds true for TextBlocks used by ContentPresenter.

For example, in the following XAML the TextBlock that is ultimately used to present the button's content will not get the implicit Style:

<Window.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Window.Resources>
<StackPanel>
    <Button Content="Will not be red" />
    <TextBlock Text="Will be red" />
</StackPanel>

If you take that exact same Style and move it to the application's Resources, then both will be red:

<Application.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Application.Resources>

So you can either move your implicit Style to application resources, which is generally not a good idea. Or you can customize the display for the specific scenario you have. This can include adding an implicit DataTemplate, or customizing a control's Template.

If you can provide more information, then it would be easier to know which is the best approach.

like image 120
CodeNaked Avatar answered Oct 23 '22 16:10

CodeNaked


Thanks to this Gist by James Nugent: "WPF style which puts character ellipsis on button contents without replacing the ContentPresenter with a TextBlock and thus losing the ability to support access keys."

This worked for me:

<ContentPresenter.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="TextTrimming" Value="CharacterEllipsis"></Setter>    
    </Style>
</ContentPresenter.Resources>
like image 8
Ben Avatar answered Oct 23 '22 14:10

Ben