XAMLを使わないWPF入門38「コードビハインドを使ったボタンのサンプル」

コンピュータ

コードビハインドの最小のサンプルコードを書いてみました。
image

image

ファイル名:NoXAML38.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 NoXAML38;

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;

namespace NoXAML38;

public class MainWindow : Window
{
    public MainWindow()
    {
        Title = "Hello WPF";
        Width = 300;
        Height = 200;

        var button = new Button
        {
            Content = "Click Me",
            Width = 100,
            Height = 30,
            Margin = new Thickness(10)
        };
        button.Click += (s, e) => MessageBox.Show("Hello!");

        // レイアウトにStackPanelを使うことでサイズ調整を自動化
        Content = new StackPanel
        {
            Children = { button }
        };
    }
}

XAMLを使わないWPFでコードビハインド開発だと、コードがかなりシンプルになります。一見するとWinFormsにも見えますが、コントロールを生成し、イベント処理を書いて、Windowに配置する一連の流れは、WinFormsのそれと重なる部分が多いためです。WPFのコントロールは自動的にレイアウトされるケースが多いので、座標の指定や幅高さの指定が省略できる点が異なります。
再利用を考えない試作や個人の小規模開発などにはこれで十分かもしれません。

コメント