Reputation: 1051
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?
Upvotes: 11
Views: 15267
Reputation: 11238
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>
Upvotes: 4
Reputation: 100620
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.
Upvotes: 6
Reputation: 59633
If you want to display HTML, use a Webbrowser control.
<WebBrowser Name="myWebBrowser"/>
And in your code, pass your text like this:
myWebBrowser.NavigateToString(myHTMLString);
If not, and bold is the only thing to be done 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
}
Upvotes: 10