Pages

2009-01-13

WPF Menu using PowerShell

Usually I use HTA for a quick application, but with PowerShell V2 it's possible to use Windows Presentation Foundation (WPF) with a lot of nice features I don't have to code from the bottom.

This little script is a investigation into the MenuItem class and click events:

$Window = New-Object Windows.Window
$Window.Title="SQLAdmin"
$Window.Height="250"
$Window.Width="400"

$SystemMenuItem = New-Object Windows.Controls.MenuItem
$SystemMenuItem.Header = "_Systems"
$SystemMenuItem.add_Click({ $Label.Content = 'SQLAdmin' })

$ManStudToolMenuItem = New-Object Windows.Controls.MenuItem
$ManStudToolMenuItem.Header = "_Management Studio"
$ManStudToolMenuItem.add_Click({ $Label.Content = 'Starting SQL Server Management Studio...' })

$ToolMenuItem = New-Object Windows.Controls.MenuItem
$ToolMenuItem.Header = "_Tools"
$ToolMenuItem.Items.Add($ManStudToolMenuItem)

$Menu = New-Object Windows.Controls.Menu
$Menu.Height="22"
$Menu.VerticalAlignment="Top"
$Menu.HorizontalAlignment="Stretch"
$Menu.Items.Add($SystemMenuItem)
$Menu.Items.Add($ToolMenuItem)

$Label = New-Object Windows.Controls.Label
$Label.Content = "This initial laben contain several lines`nof text."

$ContentCanvas = New-Object Windows.Controls.Canvas
$ContentCanvas.Margin="0,22,0,0"
$ContentCanvas.Children.Add($Label)

$Grid = New-Object Windows.Controls.Grid
$Grid.Children.Add($Menu)
$Grid.Children.Add($ContentCanvas)

$Window.Content = $Grid

[void]$Window.ShowDialog()


When the script starts, this window is shown:



Clicking the menu item "Systems" changes the contents of the white area:


The menu item "Tools" has a sub-item "Management Studio":

Clicking the menu item "Management Studio" changes the contents of the white area (again...):

Well - not exactly Rocket Science, but I found out how to use WPF MenuItem :-)
Still the formatting is done programatically. I would like to know how to use XAML for formatting and PowerShell for functionality.
References
MSDN Library > Windows Presentation Foundation
Windows PowerShell Blog : WPF & PowerShell -- Part 3 (Handling Events)
Huddled Masses : WPF From PowerShell - Select-Grid
Charles Petzold : Applications = Code + Markup (ISBN-13: 978-0-7356-1957-9)

No comments:

Post a Comment