Search code examples
wpfwpf-controlstextblock

Set textblock text which is inside user control multiline


I have a user control which contains a textblock with word wrap.

<UserControl>
  <StackPanel>
    <TextBlock MaxWidth="500"
               Margin="2"
               Text="{Binding HintHeader}"
               TextWrapping="Wrap" />

    <TextBlock MaxWidth="500"
               Margin="2"
               Text="{Binding HintBody}"
               TextWrapping="Wrap" />
  </StackPanel>
</UserControl>

Hintbody is dependency property of user control. I can use the control in other place fine as:

<cntrls:HintButton x:Name="hint"
                   Width="24"
                   Height="24"
                   Margin="85,68,0,0"
                   HintHeader="This is an header"
                   HintBody="This is an hint"/>

Everything works fine. But I want set a multiline text to the textblock (HintBody). Setting Hintbody property using "\r\n" from code behind works fine. But I want to set the same from XAML. Something like.

<cntrls:HintButton x:Name="hint"
                       Width="24"
                       Height="24"
                       Margin="85,68,0,0"
                       HintHeader="Hint Header" >
      <cntrls:HintButton.HintBody>
        This is a multiline hint body.
        <LineBreak />
        This is a multiline hint body.
      </cntrls:HintButton.HintBody>      
    </cntrls:HintButton>

Solution

  • I would recommend using a ContentPresenter instead of TextBlock inside the user control for the HintBody. That would give you greater flexibility in what you can do now and in the future.

    <UserControl>
      <StackPanel>
        <TextBlock MaxWidth="500"
               Margin="2"
               Text="{Binding HintHeader}"
               TextWrapping="Wrap" />
    
        <ContentPresenter MaxWidth="500"
               Margin="2"
               Text="{Binding HintBody}"
               TextWrapping="Wrap" />
      </StackPanel>
    </UserControl>
    

    You'd need to change the type of HintBody property to be object. Then you could do:

    <cntrls:HintButton x:Name="hint"
                       Width="24"
                       Height="24"
                       Margin="85,68,0,0"
                       HintHeader="Hint Header" >
      <cntrls:HintButton.HintBody>
        <TextBlock>
            <Run Text="This is a line."/>
            <LineBreak/>
            <Run Text="This is another line"/>
        </TextBlock>     
      </cntrls:HintButton.HintBody> 
    </cntrls:HintButton>