13

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

2 Answers 2

40

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.

0
10

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>
1
  • Very good solution, this allows the default behavior of either auto-creating a TextBox just from a string or string resource, with custom styles to the TextBox pre-defined, or allowing to define custom content if more than a simple TextBox is required. Apr 5, 2021 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.