Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TextBlock dynamic bold and italic parts

Tags:

I'm using MVVM pattern and I have string type property in my ModelView.

The string may contain following HTML tags:

<b>, </b>, <i>, </i>  

I need to make certain parts of text in TextBlock to be in normal, bold or italic.

At moment I have created workaround, a helper method that works like this:

  1. Breaks HTML string into parts

  2. Creates instance of Run class

  3. Depending on tag, sets FontWeight or FontStyle properties

  4. Adds instance of Run class to TextBlock's Inlines collection

This solution works, but it is not compatible with MVVM pattern.

I was thinking of using Convertors, but I'm not sure what property of TextBlock should I do binding to.

What do You think, how can this problem be solved?

like image 239
Daniil Harik Avatar asked Mar 31 '09 16:03

Daniil Harik


2 Answers

Something I've done in the past is to use a ContentControl, with the Content property bound to the string with a ValueConverter that returns a dynamically created TextBlock. Other solutions can be found here, including this one.

like image 53
wekempf Avatar answered Nov 15 '22 07:11

wekempf


The easiest solution that I've found for this problem.

Is to use BindableRichTextBox, that can be found at http://www.shawnduggan.com/?p=54

  1. Using Convertors convert HTML string to XAML and then make it into FlowDocument object

  2. Bind Document to BindableRichTextBox

  3. Make RichTextBox look like TextBlock (Focusable="False", BorderThinkness="0", BorderBrush="White"....etc)

like image 38
Daniil Harik Avatar answered Nov 15 '22 05:11

Daniil Harik