XAMLを使わないWPF入門31「TextAlignmentで文字を右寄せ」

コンピュータ

文字列の配置設定のプロパティを試してみます。

設定種類

  • TextAlignment.Right … 右寄せ
  • TextAlignment.Left … 左寄せ
  • TextAlignment.Center … 中央揃え
  • TextAlignment.Justify … 左寄せ?

image

ファイル名:NoXAML31.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

</Project>

ファイル名:App.cs


using System;
using System.Windows;

namespace NoXAML31;

public class App : Application
{
    [STAThread]
    public static void Main(string[] args)
    {
        var app = new App();
        app.Run();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        var win = new MainWindow();
        win.Show();
    }
}

ファイル名:AssemblyInfo.cs


using System.Windows;

[assembly:ThemeInfo(
    ResourceDictionaryLocation.None,            //where theme specific resource dictionaries are located
                                                //(used if a resource is not found in the page,
                                                // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly   //where the generic resource dictionary is located
                                                //(used if a resource is not found in the page,
                                                // app, or any theme specific resource dictionaries)
)]

ファイル名:MainWindow.cs


using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace NoXAML31;

public class MainWindow : Window
{
    public MainWindow()
    {
        this.Title = "TextAlignmentで文字を右寄せ";
        this.Width = 400;
        this.Height = 300;

        // スタックパネル
        var panel = new StackPanel
        {
            Margin = new Thickness(20)
        };

        // TextBlock(右寄せ)
        var textBlock = new TextBlock
        {
            Text = "これは右寄せのテキストです。",
            FontSize = 16,
            TextAlignment = TextAlignment.Justify,
            Width = 100,
            Height = 300,
            //Background = Brushes.LightYellow
        };

        // TextBox(右寄せ)
        var textBox = new TextBox
        {
            Text = "右寄せ入力欄",
            FontSize = 16,
            TextAlignment = TextAlignment.Left,
            Width = 100,
            Height = 300,
            //Margin = new Thickness(0, 20, 0, 0)
        };

        panel.Children.Add(textBlock);
        panel.Children.Add(textBox);
        
        this.Content = panel;
    }
}

コメント