Neal Byington Neal Byington - 1 month ago 17
C# Question

WPF - StringFormat with weighted text

I have a Question concerning WPF

stringformat
.

I want to bind a string to a
TextBlock
with a
stringformat
, currently I have something similar to the following:

<TextBlock>
<TextBlock.Text>
<Binding StringFormat="{}Text: {0}" Path="text"/>
</TextBlock.Text>
</TextBlock>


What I want to do is format the string to look as follows:
Text: text

Or in other words, I wish to Bold the first portion of the resulting string. In my research for a resolution to the problem I found a similar question, StringFormat with Font Weight. However, I'm not happy with that approach, and most suggestions echo this solution to my problem.

I would like to know if this is the only way to do this. I'm not quite happy with that solution as I feel it bloats the XML and makes it harder to read.

granted I am new to WPF overall so if this is the acceptable way I'll do so.... I just want to know if this is the best way to aproach this simple problem.

Answer

I only have one word for you: Run.

<TextBlock>
    <Run FontWeight="Bold"
         Text="Text: " />
    <Run Text="{Binding text}" />
</TextBlock>

I should read the question entirely before answering; then again, you should not just link another page without adding details from it!

From the top of my head, there are only 2 solutions to have some markup formatting, <Run> and <Span>.

<Span> has some useful shorthands for <Bold>, <Italic> and <Underline>, but these do not support binding.
<Run> is verbose heavy, but supports binding.

In your case, the 'best' solution would be something like:

<TextBlock>
    <Bold>Text: </Bold><Run Text="{Binding text}"/>
</TextBlock>

For the side note, Span is like Run, but can contains other elements (Run, Span, text).

For more details, see also.

Comments