2009-11-13

WPF Button with click event using PowerShell

A WPF Button with a click event can basically be defined either programmatic or with XAML. The two examples below gives the same look and feel in both ways.

First the programmatic way:
function Show-pgmButton {
    $Window = New-Object System.Windows.Window
    $Window.Title="SQLAdmin"
    $Window.Height="250"
    $Window.Width="400"
   
    $Button = New-Object System.Windows.Controls.Button
    $Button.Height = 23
    $Button.Width = 100
    $Button.Margin = '12,12,0,0'
    $Button.VerticalAlignment = 'Top'
    $Button.HorizontalAlignment = 'Left'
    $Button.Content = "Don't click me!"
    $Button.add_Click({
        $Button.Content = 'Arrrgh!!!'
        Start-Process '\\Titanium\Musik'
    })
    $Grid = New-Object System.Windows.Controls.Grid
    $Grid.Children.Add( $Button )
   
    $Window.Content = $Grid
    [void]$Window.ShowDialog()
}

Then the XAML way:
function Show-xamlButton {
[xml]$XAML = @'
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="SQLAdmin" Height="250" Width="400">
   <Grid>
      <Button Height="22" Width="100" Name="myButton" Content="Don't click me!" VerticalAlignment="Top" HorizontalAlignment="Left" />
   </Grid>
</Window>
'@

   $Reader = New-Object System.Xml.XmlNodeReader $XAML
   $Window = [System.Windows.Markup.XamlReader]::Load( $Reader )

   $myButton = $Window.FindName('myButton')
   $myButton.Add_Click({
      $myButton.Content = 'Arrrgh!!!'
      Start-Process '\\Titanium\musik'
   })

   [void]$Window.ShowDialog()
}

No comments: