20

In the TextBlock object you can format the text in the XAML like this:

<TextBlock>
    <Bold>bold text</Bold> random non bold next
</TextBlock>

How do you do the "Bold" tags programmatically?

I tried just putting them in the text property and it just printed them out (the tags were printed as text).

2
  • Thanks for both the great answers. Upvoted both. Picked the one I did because it was specific to my example. Commented Nov 25, 2009 at 16:42
  • 1
    More better solution: stackoverflow.com/questions/947614/… Commented Jun 24, 2013 at 17:27

3 Answers 3

21

Here is the code from the MSDN website, which I think will help (http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.aspx).

XAML

<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>
<Button Width="100" Margin="10">Click Me</Button>
<TextBlock  Name="textBlock2" 
  TextWrapping="Wrap" Background="AntiqueWhite" TextAlignment="Center"
>
  By default, a TextBlock provides no UI beyond simply displaying its contents.
</TextBlock>
<Button Width="100" Margin="10">Click Me</Button>

C#

TextBlock textBlock1 = new TextBlock();
TextBlock textBlock2 = new TextBlock();

textBlock1.TextWrapping = textBlock2.TextWrapping = TextWrapping.Wrap;
textBlock2.Background = Brushes.AntiqueWhite;
textBlock2.TextAlignment = TextAlignment.Center;

textBlock1.Inlines.Add(new Bold(new Run("TextBlock")));
textBlock1.Inlines.Add(new Run(" is designed to be "));
textBlock1.Inlines.Add(new Italic(new Run("lightweight")));
textBlock1.Inlines.Add(new Run(", and is geared specifically at integrating "));
textBlock1.Inlines.Add(new Italic(new Run("small")));
textBlock1.Inlines.Add(new Run(" portions of flow content into a UI."));

textBlock2.Text =
    "By default, a TextBlock provides no UI beyond simply displaying its contents.";
Sign up to request clarification or add additional context in comments.

Comments

20

Visual Basic Version:

Dim tb As New TextBlock

Dim b As New Bold
b.Inlines.Add(New Run("bold text"))

tb.Inlines.Add(b)
tb.Inlines.Add(New Run("random non bold text"))

C# Version:

TextBlock tb = new TextBlock();
var bold = new Bold(new Run("Bold Text"));
tb.Inlines.Add(bold);

var normal = new Run("Normal Text"));
tb.Inlines.Add(normal);

1 Comment

Does anybody know a way like tb.Inlines.Clear(); tb.Inlines.Add(Parse(myXamlText)); </code> ?
0

Try this:

textBlock1.FontWeight = Windows.UI.Text.FontWeights.Bold;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.