[WPF][TextBox] VerticalAlignmentプロパティを使用してテキストの水平方向の配置を設定する

スポンサーリンク

概要

WPF の TextBox コントロールでは、VerticalAlignment プロパティを使用して、テキストの垂直方向の配置を調整することができます。この記事では、VerticalAlignment プロパティの設定方法とテキストの水平配置について解説します。

 

構文

textBox.VerticalAlignment = VerticalAlignment.Center;

上記のコードは、VerticalAlignmentプロパティを使用してテキストの垂直方向の配置を中央に設定している例です。

VerticalAlignmentプロパティには、以下の値を設定することができます。

説明
Top テキストを上寄せに配置します。
Center テキストを中央に配置します。
Bottom テキストを下寄せに配置します。

 

使用例

このコードは、TextBox と RadioButton を使用して、VerticalAlignment プロパティの使用例を示しています。RadioButton の選択に応じて、TextBox のテキストのVerticalAlignment が変更されます。

XAMLコード例

<StackPanel>
  <RadioButton Content="Top" IsChecked="True" Checked="RadioButton_Checked"/>
  <RadioButton Content="Center" Checked="RadioButton_Checked"/>
  <RadioButton Content="Bottom" Checked="RadioButton_Checked"/>

  <TextBox x:Name="textBox" Text="Sample Text" Width="200" Height="300" />
</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 "Top":
                textBox.VerticalAlignment = VerticalAlignment.Top;
                break;
            case "Center":
                textBox.VerticalAlignment = VerticalAlignment.Center;
                break;
            case "Bottom":
                textBox.VerticalAlignment = VerticalAlignment.Bottom;
                break;
        }
    }
}

XAML の部分では、StackPanel を使用してRadioButton と TextBox を構成しています。RadioButton は VerticalAlignment プロパティの使用可能な値(Top、Center、Bottom)を表示します。

C#の部分では、RadioButton_Checkedというイベントハンドラが定義されています。このイベントハンドラは、RadioButtonが選択されたときに呼び出されます。

RadioButton_Checkedイベントハンドラでは、選択されたRadioButtonのContent(表示されているテキスト)を取得します。そして、取得したContentに基づいて、TextBoxのVerticalAlignmentプロパティを設定します。

選択されたRadioButtonが「Top」の場合、TextBoxのVerticalAlignmentはVerticalAlignment.Topに設定されます。同様に、「Center」ならVerticalAlignment.Center、「Bottom」ならVerticalAlignment.Bottomが設定されます。

これにより、ユーザーがRadioButtonを選択すると、TextBoxのテキストのVerticalAlignmentが対応する値に変更されます。

Please follow and like us:

コメント

タイトルとURLをコピーしました