WPF: TextTrimming on a ContentPresenter

Posted on

Problem :

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?


Solution :

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:

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

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

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

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.

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:

    <Style TargetType="TextBlock">
        <Setter Property="TextTrimming" Value="CharacterEllipsis"></Setter>    

Leave a Reply

Your email address will not be published. Required fields are marked *