Neal Byington Neal Byington - 11 months ago 104
C# Question

WPF - StringFormat with weighted text

I have a Question concerning WPF


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

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

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 Source

I only have one word for you: Run.

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

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:

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

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

For more details, see also.