Powershell WPF Xamlファイルを用意せずGUIフォームを作成する例

PowerShell

System.Windows.WindowをObject化し実装すれば、Xamlファイルを用意せず、ゴリゴリとGUIフォームを作成する例

Xamlファイルを用意するよりも、昔ながらのゴリゴリとフォ作成する手法も取り入れて、GUIフォームを作成する方が、Powershell的にはやりやすい場合もありそう。

今の自分のスキルだと、こちらの方が馴染むかも。

サンプルコード

Add-Type -AssemblyName PresentationFramework
# Create a window object
$Window = New-Object System.Windows.Window
$Window.SizeToContent = [System.Windows.SizeToContent]::WidthAndHeight
$Window.Title = "WPF Window"
$window.WindowStartupLocation = [System.Windows.WindowStartupLocation]::CenterScreen
$Window.ResizeMode = [System.Windows.ResizeMode]::NoResize
# Create a textbox object
$TextBox = New-Object System.Windows.Controls.TextBox
$TextBox.Height = 85
$TextBox.HorizontalContentAlignment = "Center"
$TextBox.VerticalContentAlignment = "Center"
$TextBox.FontSize = 30
# Create a button object
$Button = New-Object System.Windows.Controls.Button
$Button.Height = 85
$Button.HorizontalContentAlignment = "Center"
$Button.VerticalContentAlignment = "Center"
$Button.FontSize = 30
$Button.Content = " Plus Click Me "
# Create a button object
$Button2 = New-Object System.Windows.Controls.Button
$Button2.Height = 85
$Button2.HorizontalContentAlignment = "Center"
$Button2.VerticalContentAlignment = "Center"
$Button2.FontSize = 30
$Button2.Content = " Minus Click Me "
# Assemble the window
$StackPanel = New-Object System.Windows.Controls.StackPanel
$StackPanel.Margin = "5,5,5,5"
$StackPanel.AddChild($TextBox)
$StackPanel.AddChild($Button)
$StackPanel.AddChild($Button2)
$Window.AddChild($StackPanel)
#init
$TextBox.Text = [int]10
# Add an event for the button click
$Button.Add_Click{
# Get the current value
[int]$CurrentValue = $TextBox.Text
# Plus
$CurrentValue ++
# Update the text property with the new value
$TextBox.Text = $CurrentValue
}
$Button2.Add_Click{
# Get the current value
[int]$CurrentValue = $TextBox.Text
#Minus
$CurrentValue --
# Update the text property with the new value
$TextBox.Text = $CurrentValue
}
$Window.ShowDialog() | Out-Null
Write-Host "Ret=" $TextBox.Text
#オブジェクトをxamlファイル化
$xaml = [System.Windows.Markup.XamlWriter]::Save($Window)
Write-Host $xaml
#出来上がったxamlファイルをテキスト出力
$DeskTop = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
$xamlFilePath = $DeskTop + "\WPFSample.xaml"
[System.IO.File]::WriteAllText($xamlFilePath, $xaml, [System.Text.Encoding]::UTF8)

実行結果

PlusやMinusをクリックするとTextBoxの変数が変化する。

最後に$TextBox.Textの結果をコンソールに表示させる。

オブジェクトはXamlファイルで出力できる

ゴリゴリ作ったWindowオブジェクトをxamlファイルとして出力させることも可能

参考にさせて頂いたサイト

PowerShellでWPFのダイアログを表示する : morituriのブログ
Windowsフォームと同じような方法で、WPFのダイアログを作ることもできる。 ※Windowsフォームを使う場合:powershellでWindowsフォームのモーダルダイアログを表示する ※書き方をちょっと改善する記事:PowerSh...
PowerShell DeepDive: WPF, Data Binding and INotifyPropertyChanged
PowerShell can be used to create some nice UI front-ends using the Windows Presentation Framework (WPF). You can create ...

コメント

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