Building Cross-Platform WPF-Style Applications in PowerShell Core

With PowerShell Pro Tools 4.5.0, you can now take advantage of the Avalonia project in PowerShell Core. Avalonia is a WPF-inspired cross-platform XAML-based UI framework providing a flexible styling system and supporting a wide range of OSs: Windows (.NET Framework, .NET Core), Linux (GTK), MacOS, Android and iOS. PowerShell Pro Tools bridges the gap between PowerShell Core and Avalonia.

Avalonia is currently in beta so there may be some bugs. These cmdlets only work in PowerShell Core.

Creating a basic application

Simple to WPF, Avalonia uses XAML to define the look and feel of the application. Many of the control names and concepts are very similar. To create a basic Avalonia PowerShell application, you first need to define some XAML.

$Xaml = '<Window xmlns="https://github.com/avaloniaui"
        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
	<Button Width="160" Name="button">My Button</Button>
        <TextBox HorizontalAlignment="Left" Margin="12,12,0,0" Name="txtDemo" VerticalAlignment="Top" Width="500" Height="25" />

This particluar form has a single textbox and button. They fall within a StackPanel. All these controls should seem very similar to WPF.
In order to create a new Avalonia window, you can use the PowerShell Pro Tools ConvertTo-AvaloniaWindow cmdlet to create a new window.

$window = ConvertTo-AvaloniaWindow -Xaml $Xaml

After creating a window, you may want to adjust the behavior of the button and textbox. To do so, you can find the control using the Find-AvaloniaControl cmdlet.

$Button = Find-AvaloniaControl -Name 'button' -Window $Window
$txtDemo = Find-AvaloniaControl -Name 'txtDemo' -Window $Window

Next, very similar to WPF, we can now add event handlers to the controls that we just found. This event handler is invoked when the button is clicked. It then sets the textbox’s value to “Hello, World from (Operating System) running PowerShell Core (Version)!”

$Button.add_Click({$txtDemo.Text = "Hello, World from $($PSVersionTable.OS) running PowerShell Core $($PSVersionTable.PSVersion)"})

Finally, we display the window using Show-AvaloniaWindow.

Show-AvaloniaWindow -Window $Window

If you run this script on Windows, you’ll see the following.

Running Avalonia on Windows

Here is the exact same script running from a Ubuntu Linux machine.

Running Avalonia on Linux

This functionality is part of the PowerShell Pro Tools module. This is also included with the PowerShell Pro Tools extension for VS Code.

Leave a Reply