问题
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