for WPF developers
テキストを表示するためのコントロールです。 Text プロパティにテキストを直接指定したり、 System.Windows.Documents.Run クラスによるインラインレベルフローコンテンツ要素を指定したりすることでテキストを指定できます。
ページ内リンク
もっとも基本的な使い方は次のように Text プロパティにテキストを直接指定する方法です。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="100" Width="200">
<Grid>
<TextBlock Text="サンプルテキスト" />
</Grid>
</Window>
ここで、一体どの領域が TextBlock コントロールなのでしょうか。わかりやすくするために背景色を付けてみます。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="100" Width="200">
<Grid>
<TextBlock Text="サンプルテキスト" Background="Yellow" />
</Grid>
</Window>
ここで、テキストを中央に描画させようとしたとき、2 つの方法が考えられます。 ひとつは TextBlock コントロールの中でテキストの位置をセンタリングする方法で、 もうひとつは TextBlock コントロール自体を Grid コントロールの中央に配置する方法です。
TextBlock コントロールの中でテキストの位置をセンタリングするには、TextAlignment プロパティを使用します。
<TextBlock Text="サンプルテキスト" Background="Yellow" TextAlignment="Center" />
<TextBlock Text="サンプルテキスト" Background="Yellow" HorizontalAlignment="Center" />
このように、水平方向は TextAlignment プロパティがありますが、 垂直方向の位置を変更する場合は VerticalAlignment プロパティで TextBlock コントロール自体の配置を変更しなければなりません。
項目名などは 1 行でいいかもしれませんが、ちょっとした説明文などを表示する場合、テキストが複数行になる場合があります。
このようなときは、次のように Run および LineBreak というインラインレベルフローコンテンツ要素を使用します。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="250">
<Grid>
<TextBlock>
<Run Text="サンプルテキスト" />
<LineBreak />
<Run Text="<LineBreak /> で改行できます。" />
</TextBlock>
</Grid>
</Window>
LineBreak は意図した位置で改行させることができますが、
ウィンドウのサイズなどによって相対的に改行させたい場合は、TextWrapping プロパティを使用します。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="250">
<Grid>
<TextBlock Text="これはとても長い文章を表現するためのサンプルテキストです。TextWrapping プロパティで自動的に改行させることができます。" TextWrapping="Wrap" />
</Grid>
</Window>
Designed by CSS.Design Sample