WPF: TextTrimming on a ContentPresenter

我与影子孤独终老i 提交于 2019-11-30 03:39:50

问题


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!


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/5810919/wpf-texttrimming-on-a-contentpresenter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!