04 May 2010

WPF: Bolding a portion of text in a TextBlock

I am using WPF and .NET 4 in my latest project and I ran into a bit of a snag, trying to figure out how to display formatted text in a TextBlock programmatically. The process is far from obvious, so I thought I'd capture it here.

The following code makes a part of the text bold:

      
TextBlock fileNameStatus;
...
// Usually we need to clear the TextBlock text
fileNameStatus.Inlines.Clear();
fileNameStatus.Inlines.Add("Editing file: "); // Plain text
Run textRun = new Run(_fileName);
textRun.FontWeight = FontWeights.Bold; // Bold text
fileNameStatus.Inlines.Add(textRun);

The control of the font is done through the Run type and its FontXXX properties.

No comments: