Silverlight Tip of the Day #45: Text Formatting with the TextBlock control
Silverlight comes with a very useful control called TextBlock. This control allows you to render read only text. Displaying text via this control is as easy as:
<TextBlock Text="Hello There"></TextBlock>
There are also a variety of options you can apply to your font. These include:
1. FontFamily. The font typeface family name.
<TextBlock FontFamily="Courier New">Hello There</TextBlock>
<TextBlock FontFamily="Times New Roman" Canvas.Top="10">Hello There</TextBlock>
<TextBlock FontFamily="Verdana" Canvas.Top="20">Hello There</TextBlock>
2. FontSize. The font size in pixels.
<TextBlock FontSize="10">Hello There</TextBlock>
<TextBlock FontSize="20" Canvas.Top="20">Hello There</TextBlock>
<TextBlock FontSize="30" Canvas.Top="50">Hello There</TextBlock>
2 FontStetch. Options include:
Note that the support for the above options will depend upon the font you are using.
3 FontWeight. Options include: Thin, ExtraLight, Light, Normal, Medium, SemiBold, Bold, ExtraBold, Black, ExtraBlack.
Note that the support for the above options will depend upon the font you are using.
<TextBlock Text="Hello There" FontWeight="Normal" Canvas.Top="0"></TextBlock>
<TextBlock Text="Hello There" FontWeight="Bold" Canvas.Top="10"></TextBlock>
4 FontStyle: Options include: Normal, Italic
<TextBlock Text="Hello There" FontStyle="Normal" Canvas.Top="0"></TextBlock>
<TextBlock Text="Hello There" FontStyle="Italic" Canvas.Top="10"></TextBlock>
5. Foreground. This allows you to change the color of the font. You can use brushes including solid color, gradient, image or video brushes to create a wide variety of effects.
<TextBlock Text="Hello There" FontSize="20" FontFamily="Arial" Canvas.Top="0"> <TextBlock.Foreground>
<LinearGradientBrush>
<GradientStop Color="#FF0000FF" Offset="0.0" />
<GradientStop Color="#FFEEEEEE" Offset="1.0" />
</LinearGradientBrush>
</TextBlock.Foreground>
</TextBlock>
<TextBlock Text="Hello There" FontSize="20" FontFamily="Arial" Canvas.Top="20" Foreground="Red"></TextBlock>
6. TextDecorations. A text decoration is a visual ornament that you can add to text. Currently the only supported decoration is underline.
<TextBlock TextDecorations="underline">Hi there</TextBlock>
7. Runs. Last, you can inter-mix different runs of text formatting within the same block using the Run element. For example, you can display a string like this:
<TextBlock>
<Run FontWeight="Bold">Hello There.</Run>
<Run Foreground="Red">How are you?</Run>
<Run FontStyle="Italic">I am fine thanks!</Run>
<Run>漢字</Run>
</TextBlock>
Thank you,
--Mike Snow
Subscribe in a reader