概要
WPF の TextBox コントロールでは、TextAlignment プロパティを使用して、テキストの水平方向の配置を調整することができます。この記事では、TextAlignment プロパティの設定方法とテキストの水平配置について解説します。
構文
textBox.TextAlignment = TextAlignment.Center;
上記のコードは、TextAlignmentプロパティを使用してテキストの水平方向の配置を中央に設定している例です。
TextAlignmentプロパティには、以下の値を設定することができます。
値 | 説明 |
---|---|
Left | テキストを左寄せに配置します。 |
Center | テキストを中央に配置します。 |
Right | テキストを右寄せに配置します。 |
Justify | テキストを少し揃えて配置します。 |
使用例
このコードは、TextBox と RadioButton を使用して、TextAlignment プロパティの使用例を示しています。RadioButton の選択に応じて、TextBox のテキストのTextAlignment が変更されます。
XAMLコード例
<StackPanel> <RadioButton Content="Left" IsChecked="True" Checked="RadioButton_Checked"/> <RadioButton Content="Center" Checked="RadioButton_Checked"/> <RadioButton Content="Right" Checked="RadioButton_Checked"/> <RadioButton Content="Justify" Checked="RadioButton_Checked"/> <TextBox x:Name="textBox" Text="Sample Text" Width="200" Height="100" /> </StackPanel>
コードビハインドのコード例
private void RadioButton_Checked(object sender, RoutedEventArgs e) { if (sender is RadioButton radioButton && radioButton.IsChecked == true) { string alignment = radioButton.Content.ToString(); switch (alignment) { case "Left": textBox.TextAlignment = TextAlignment.Left; break; case "Center": textBox.TextAlignment = TextAlignment.Center; break; case "Right": textBox.TextAlignment = TextAlignment.Right; break; case "Justify": textBox.TextAlignment = TextAlignment.Justify; break; } } }
XAML の部分では、StackPanel を使用してRadioButton と TextBox を構成しています。RadioButton は TextAlignment プロパティの使用可能な値(Left、Center、Right、Justify)を表示します。
C#の部分では、RadioButton_Checkedというイベントハンドラが定義されています。このイベントハンドラは、RadioButtonが選択されたときに呼び出されます。
RadioButton_Checkedイベントハンドラでは、選択されたRadioButtonのContent(表示されているテキスト)を取得します。そして、取得したContentに基づいて、TextBoxのTextAlignmentプロパティを設定します。
選択されたRadioButtonが「Left」の場合、TextBoxのTextAlignmentはTextAlignment.Leftに設定されます。同様に、「Center」ならTextAlignment.Center、「Right」ならTextAlignment.Right、「Justify」ならTextAlignment.Justify が設定されます。
これにより、ユーザーがRadioButtonを選択すると、TextBoxのテキストのTextAlignmentが対応する値に変更されます。
コメント