DevOps | Scripts | Automation

PowershellWPF

Create GUI with WPF in PowerShell – Part IV

Before going into deep to this article, if you haven’t read through previous articles please follow the link below.

https://theautomationcode.com/create-gui-with-wpf-in-powershell-part-i/ (Part-I)
https://theautomationcode.com/create-gui-with-wpf-in-powershell-part-ii/ (Part-II)
https://theautomationcode.com/create-gui-with-wpf-in-powershell-part-iii/ (Part-III)

In the previous article, we have written a code for controls and GUI. The output of the form will be as below.

Once the code is ready, we will add forms functionality. To proceed, we need to create an object for each control so that properties and methods of that control can be used. We are not going to describe all the methods and properties of the control but only they needed to implement this form.

Here, how we will use the unique property of the control called “Name” to assign them into the object as shown in below commands. Inside round brackets, we have used the name property of the control.


$button = $window.FindName("Submitbtn")
$txtbx = $window.FindName("InputText")
$output = $window.FindName("outlabel")

Now we need the input of the text box should be displayed in the label. The textbox has a Text property and label has a Content property that is used to retrieve or to grab the value but here all these should be done with button functionality in this example and button control supports the Add_Click method to work when the button is clicked.

You can search various properties and methods of the windows controls in Microsoft website.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.textbox?view=net-5.0

Code shown below is to implement the functionality as described above.

$button.add_click({
    $output.Content = $txtbx.Text
})

Full Script:

Add-Type -AssemblyName PresentationFramework
[XML]$form = @"
   <Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="First GUI" Height="450" Width="800" Background="#FFA09797">
    <Grid>
        <Button Name="Submitbtn" Content="Button" HorizontalAlignment="Left" Margin="340,33,0,0" VerticalAlignment="Top" Width="138" Height="37" Background="#FF99B48C"/>
        <TextBox Name="Inputtext" HorizontalAlignment="Left" Height="37" Margin="55,33,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
        <Label Name="outlabel" Content="Output " HorizontalAlignment="Left" Margin="137,110,0,0" VerticalAlignment="Top" Width="341" Height="32" Background="#FF9B3939"/>

    </Grid>
   </Window>

"@

$NR = (New-Object System.Xml.XmlNodeReader $form)
$window = [Windows.Markup.XamlReader]::Load($NR)

$button = $window.FindName("Submitbtn")
$txtbx = $window.FindName("Inputtext")
$output = $window.FindName("outlabel")

$button.add_click({
    $output.Content = $txtbx.Text
})

$window.ShowDialog()

Output: