Creating WPF Windows

by Jul 1, 2016

WPF is a great technique to create user interfaces in PowerShell. Most of the window content can be defined using XAML, a description similar to HTML but based on XML. The sample creates a "Fire Alarm" message window, and you can change text, font, size, and other details by simply editing the values inside the XAML description – no programming required:

Add-Type -AssemblyName PresentationFramework
  

$xaml = @'
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns_x="http://schemas.microsoft.com/winfx/2006/xaml"
   SizeToContent="WidthAndHeight"
   Title="Get Out!"
   Topmost="True">
      <TextBlock
         Margin="50"
         HorizontalAlignment="Center"
         VerticalAlignment="Center"
         FontFamily="Stencil"
         FontSize="80"
         FontWeight="Bold"
         Foreground="Red">
         Fire Alarm!
      </TextBlock>
</Window>
'@

$reader = [System.XML.XMLReader]::Create([System.IO.StringReader]$XAML)
$window = [System.Windows.Markup.XAMLReader]::Load($reader)
  
$window.ShowDialog()

Twitter This Tip! ReTweet this Tip!