Make some text bold inside a TextBlock

I know that we can use <Run> in XAML to achieve what I ask:

 <TextBlock.Inlines> <Run Text="This is" /> <Run FontWeight="Bold" Text="Bold Text." /> </TextBlock.Inlines> 

I can also do this in code as follows:

 TextBlock.Inlines.Add(new Run("This is")); TextBlock.Inlines.Add(new Bold(new Run("Bold Text."))); 

But my problem is something else:

Suppose I have the following text in my database:

 This is <b>Bold Text</b>. 

Now my Textblock is bound to a field that contains the above text in the database.

I want text between <b> and </b> to be bold . How can I achieve this?

+6
source share
3 answers

If you want to display HTML, use the Webbrowser control.

 <WebBrowser Name="myWebBrowser"/> 

And in your code, pass the text as follows:

 myWebBrowser.NavigateToString(myHTMLString); 

If not, and bold is the only thing to do and cannot be nested, you can do it like this:

 string s = "<b>This</b> is <b>bold</b> text <b>bold</b> again."; // Sample text var parts = s.Split(new []{"<b>", "</b>"}, StringSplitOptions.None); bool isbold = false; // Start in normal mode foreach (var part in parts) { if (isbold) myTextBlock.Inlines.Add(new Bold(new Run(part))); else myTextBlock.Inlines.Add(new Run(part)); isbold = !isbold; // toggle between bold and not bold } 
+7
source

It looks like you want to replace your custom formatting with <Bold> - see TextBlock for more information. Sample from the article:

 <TextBlock Name="textBlock1" TextWrapping="Wrap"> <Bold>TextBlock</Bold> is designed to be <Italic>lightweight</Italic>, and is geared specifically at integrating <Italic>small</Italic> portions of flow content into a UI. </TextBlock> 

One approach is to reformat the string according to the expected TextBlock .

If you have HTML input, first parse the text with HtmlAgilityPack, and then go through the resulting elements and build a line with b elements replaced with text wrapped with <Bold> and similar to another formatting.

If you know that the database content has only valid start and end pairs (not random HTML), you can even get away with the underlying String.Replace : text = text.Replace ("," ")`.

If you have your own formatting (for example, *boldtext* ), for this you need to create your own parser.

+3
source

You can subscribe to the TargetUpdated event:

  void textBlock_TargetUpdated(object sender, DataTransferEventArgs e) { string text = textBlock.Text; if (text.Contains("<b>")) { textBlock.Text = ""; int startIndex = text.IndexOf("<b>"); int endIndex = text.IndexOf("</b>"); textBlock.Inlines.Add(new Run(text.Substring(0, startIndex))); textBlock.Inlines.Add(new Bold(new Run(text.Substring(startIndex + 3, endIndex - (startIndex + 3))))); textBlock.Inlines.Add(new Run(text.Substring(endIndex + 4))); } } 

and XAML for TextBlock :

 <TextBlock x:Name="textBlock" Text="{Binding NotifyOnTargetUpdated=True}"></TextBlock> 
+3
source

All Articles