Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 606
Adam Flynn Avatar asked Oct 19 '10 16:10

Adam Flynn


1 Answers

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.

like image 183
Aaron McIver Avatar answered Oct 21 '22 21:10

Aaron McIver