I know that we can use <Run>
in XAML to achieve what I am asking :
<TextBlock.Inlines>
<Run Text="This is" />
<Run FontWeight="Bold" Text="Bold Text." />
</TextBlock.Inlines>
Also I can do it in code behind as follows:
TextBlock.Inlines.Add(new Run("This is"));
TextBlock.Inlines.Add(new Bold(new Run("Bold Text.")));
But my problem is something different:
Suppose I have 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 database.
I want the text between <b> and </b> to be bold
. How can I achieve this?
With the cursor on top of the text box, right click, then select Font and then Font Style "Bold".
Wrap a word in string with '<b>' to make it Bold without changing word's original case.
textBlock. Inlines. Add(new Run(Boldsplist) { FontWeight = FontWeights. Bold }); this.
TextBlock is not editable.
It looks like you want to replace your custom formatting with <Bold>
- see TextBlock for more info. 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 re-format string to match what TextBlock
expects.
If you have HTML input - parse the text with HtmlAgilityPack first and than walk though resulting elements and construct string with b
-elements replaced with text wrapped <Bold>
and similar to other formatting.
If database content is known to have only valid begin/end pairs (not random HTML) you may even get away with basic String.Replace
: text = text.Replace( "", "")`.
If you have you own custom formatting (like *boldtext*
) you'll need to invent custom parser for that.
You can subscribe to 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 the TextBlock
:
<TextBlock x:Name="textBlock" Text="{Binding NotifyOnTargetUpdated=True}"></TextBlock>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With