wafers
wafers

Reputation: 1241

How can I format text in a TextBlock?

I am trying to make a single block of text composed of multiple TextBlocks

- THE TARGET

For example, I want to achieve like the line below:

The way I'm trying to do is

<StcakPanel Orientation="Horizontal" Width="400" >

   <TextBlock Text="I read this line in a " TextWrapping="Wrap" />
   <TextBlock Text="ListBox"  FontStyle="Italic" TextWrapping="Wrap"/>
   <TextBlock Text=", notice the multiple " TextWrapping="Wrap" />
   <TextBlock Text="text formatting" FontWeight="Bold" TextWrapping="Wrap"/>

<StcakPanel>

- THE PROBLEM

The text does not fit in the StackPanel, despite of setting TextWrapping for TextBlocks and Width for StackPanel.

I want to generate this code at runtime. I don't know how many words do I need to format.

Kind of showing SearchResults with highlighted search keywords.

- THE QUESTION

How can the above target be achieved either using StackPanel or something else? Having the following constraints.

Thanks very much

Upvotes: 1

Views: 445

Answers (1)

qJake
qJake

Reputation: 17139

You should use a single <TextBlock> which can contain multiple <Run>s that can each have their own formatting. If you want to insert a linebreak, you can use the <Linebreak /> control.

<StackPanel Orientation="Horizontal" Width="400" >
    <TextBlock>
       <Run Text="I read this line in a" />
       <Run Text="ListBox" FontStyle="Italic" />
       <Run Text=", notice the multiple" />
       <Run Text="text formatting" FontWeight="Bold" />
    </TextBlock>
<StackPanel>

At that point you probably don't even need the <StackPanel> unless you are going to have multiple <TextBlocks> stacked on top of one another.

See this post for more information and examples: http://www.danderson.me/posts/working-with-the-wpf-textblock-control/


To databind multiple runs within a TextBlock, see this answer: Databinding TextBlock Runs in Silverlight / WP7

Upvotes: 2

Related Questions