In the latest version of PowerShell Pro Tools for Visual Studio, I released the first version of WPF Designer support for PowerShell projects. In this post, we will look at the steps required to create a new WPF window and hook up a button click event.
Installing the necessary tools
You will need the following:
- For Visual Studio 2017
- For Visual Studio 2015
Creating a Project
You can create a module or script project.
Select the Module or Script project type, name it and then click Ok.
Right click on your project to create a new file and select the PowerShell WPF Window item template.
After creating your WPF window, you will see the same designer you would for a C# or VB.NET project.
A code behind file is automatically created that contains a PowerShell script capable of loading the XAML and running the WPF window.
Pressing F5 or clicking the Start button on the menu will launch your WPF window.
Wiring up Event Handlers
In order to enable execution of actions based on different events, you’ll want to hook up some event handlers. To do so, the first thing you’ll need to do is name your control. Named controls are currently a requirement for event handlers.
Next, select the event you would like wired up, enter a name for the event handler function and press enter.
The code behind generator will create a bunch of code to wire your event handler function to your control.
The first section removes the actual event handler XML attribute from the XAML. This is because PowerShell doesn’t actually support this type of event binding. I’ll look into supporting it somehow in the future but for now the event handlers in the XAML are placeholders for what is created in the code behind. They are removed at runtime.
The next piece of generated code is for variables that define the controls within your XAML. Currently, only the control you are adding an event handler for is generated in this section. In the future, all named controls will show up here. This allows PowerShell scripts to interact with the live controls.
Finally, we create an event handler function and wire it to the event on the control.
From here, we can define logic in the onClick function to take actions like opening a message box.
The WPF Designer is currently in beta. Please feel free to try it out in either Visual Studio 2015 or 2017. What you can expect after beta:
- Improved formatting of code
- Support for WPF dispatcher to ensure responsive UIs
- Generation of variables for all named controls
- Automatic naming of unnamed controls to support PowerShell code behind
Have questions or comments? I would love to here them!