WPF 4 ContentPresenter TextWrapping style is not applied to implicitedly generated TextBlock

我与影子孤独终老i 提交于 2019-11-27 18:03:34

问题


If I assign a piece of text to the Content property of a ContentPresenter, a TextBlock control is generated by the ContentPresenter at render time to contain that text.

If I create a style that applies toTextBlock properties and assign it to that ContentPresenter, the does not appear to apply to the implicitly generated TextBlocks.

<Style x:Key="SampleStyle">
  <Setter Property="TextBlock.TextWrapping" Value="Wrap"/>
</Style>

<ContentPresenter Content="This is a Test piece of text." Style="{StaticResource SampleStyle}"/>

Is there a way to apply this style successfully to the autogenerated TextBlocks short of applying it to all TextBlocks (e.g. declaring style as TargetType="TextBlock" with no Key)?


回答1:


You can do this...

<Window.Resources>
    <ResourceDictionary>
        <Style TargetType="{x:Type TextBlock}" x:Key="WrappingStyle">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </ResourceDictionary>
</Window.Resources>

...then where you define your ContentPresenter...

<ContentPresenter Content="This text is going to wrap...">
            <ContentPresenter.Resources>
                <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource WrappingStyle}"/>
            </ContentPresenter.Resources>
</ContentPresenter>

The TargetType is set since as you know the ContentPresenter will not always hold a TextBlock in it.




回答2:


If you are not using the style elsewhere, you could apply it directly to the content presenter:

<ContentPresenter.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="TextWrapping" Value="Wrap"/>
    </Style>
</ContentPresenter.Resources>


来源:https://stackoverflow.com/questions/3970285/wpf-4-contentpresenter-textwrapping-style-is-not-applied-to-implicitedly-generat

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