开发者

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!


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜