Create GUI with WPF in PowerShell – Part II
In part-I, we have seen how to open a new project page studio and name of the required sections on the VS page.
Continuing to this article, we will first import XAML code into PowerShell ISE or any other editor and delete a few XAML components because when we convert XAML code to XML that PowerShell can’t recognize the code. In the last part, we have created below GUI and its XAML code was displayed in the code section.
<Window x:Class="FirstGUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FirstGUI"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
You just need 2 lines between <Window></Window> tag and remove rest others.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="MainWindow" Height="450" Width="800">
So your XAML code would something like this.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
Before converting the XAML code to XML we first need to load the Presentation Framework assembly and that can be done with the below code.
Add-Type -AssemblyName PresentationFramework
Now, Store the XAML code into an array and convert it into XML.
[XML]$form = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
"@
$Form variable and Window property will show the GUI properties like Title, Height, Width etc.
Once you have XML code then need to create an object for the XML reader and then this object needs to pass to XAML reader. Code is shown below.
$NR = (New-Object System.Xml.XmlNodeReader $form)
$window = [Windows.Markup.XamlReader]::Load($NR)
We have now the GUI code ready, to display the GUI window, we need to run ShowDialog() method.
$window.ShowDialog()
Overall script will be as below.
Add-Type -AssemblyName PresentationFramework
[XML]$form = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
"@
$NR = (New-Object System.Xml.XmlNodeReader $form)
$window = [Windows.Markup.XamlReader]::Load($NR)
$window.ShowDialog()
Once you run the above code, GUI box will appear.
In the next part, we will add few more controls (buttons, textbox and label) in the GUI and in XAML code they are added inside the <grid></grid> and that time we also need to modify some XAML code to work correctly in PowerShell.