Search code examples
wpfxamlnewlinetextblock

TextBlock line break from dymamic resources


There is some markup for resources (
 is a analog of \r\n)

    <Application.Resources>
      <system:String x:Key="key1">Line1&#x0d;&#x0a;Line2</system:String>
    </Application.Resources>

and for main window:

   <Grid>
      <TextBlock Text="{DynamicResource key1}"/>
   <Grid>

But the result is only one line: "Line1 Line2". What is wrong?


Solution

  • TextBlock ignores whitespace when using its Text property. The only way to add line breaks is to use the Inlines property. While this is a read-only property that cannot be set directly, it is also the content property of the TextBlock, and thus can be set like so:

    <TextBlock>
        <StaticResource ResourceKey="key1" />
    </TextBlock>
    

    You will not be able to use DynamicResource though, since Inlines is not a dependency property.

    Also, for whitespace to be preserved in XML, you will need to add xml:space="preserve" to your string (xml is a predefined namespace, no need to declare it):

    <system:String xml:space="preserve" x:Key="key1">Line1&#x0d;&#x0a;Line2</system:String>