XAMLを使わないWPFプロジェクトを作成するPowerShellスクリプトを作成しました。
ファイル名:Create-NoXAMLProject.ps1
<#
.SYNOPSIS
WPF NoXAMLアプリのスケルトン(骨組み)プロジェクトを自動生成します。
.DESCRIPTION
指定したプロジェクト名のディレクトリを作成し、NoXAML形式(App.xamlやMainWindow.xaml未使用)の
WPFプロジェクト(.NET 8対応)を自動構成します。
プロジェクト名省略時はカレントディレクトリで生成します。
.PARAMETER ProjectName
作成するプロジェクト名。省略時はカレントディレクトリでスケルトンを生成します。
.EXAMPLE
# 新規MyAppディレクトリにNoXAMLプロジェクトを生成
.\Create-NoXAMLProject.ps1 -ProjectName MyApp
# 既存ディレクトリでNoXAMLプロジェクト生成
cd MyApp
..\Create-NoXAMLProject.ps1
#>
param(
[string]$ProjectName
)
if ($ProjectName) {
$Directory = "./$ProjectName"
# 1. プロジェクトフォルダの作成
if (!(Test-Path $Directory)) {
New-Item -ItemType Directory -Path $Directory | Out-Null
}
# 2. プロジェクトフォルダへ移動
Set-Location $Directory
} else {
$Directory = Get-Location
}
# 3. dotnet new wpf -f net8.0 で初期プロジェクト生成
dotnet new wpf -f net8.0 --force
# 4. 不要ファイル削除(XAMLとProgram.csを削除)
Remove-Item ".\App.xaml*" -Force -ErrorAction SilentlyContinue
Remove-Item ".\MainWindow.xaml*" -Force -ErrorAction SilentlyContinue
Remove-Item ".\Program.cs" -Force -ErrorAction SilentlyContinue
# プロジェクト名の決定
if (-not $ProjectName) {
# カレントディレクトリ名をプロジェクト名に
$ProjectName = Split-Path -Leaf $Directory
}
# App.cs生成(エントリポイント含む)
$app = @"
using System;
using System.Windows;
namespace $ProjectName;
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();
}
}
"@
Set-Content -Encoding UTF8 ".\App.cs" $app
# MainWindow.cs生成
$window = @"
using System.Windows;
using System.Windows.Controls;
namespace $ProjectName;
public class MainWindow : Window
{
public MainWindow()
{
this.Title = "NoXAML MainWindow";
this.Width = 400;
this.Height = 300;
var grid = new Grid();
var label = new Label
{
Content = "Hello, NoXAML World!",
FontSize = 24,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
};
grid.Children.Add(label);
this.Content = grid;
}
}
"@
Set-Content -Encoding UTF8 ".\MainWindow.cs" $window
Write-Host "NoXAMLスケルトン(エントリポイントApp.cs)生成完了: $Directory"
生成されたプロジェクトのスケルトンコード実行すると、ラベルに文字が表示されるWindowが起動します。
コメント