I’ve posted a number of times about WPF and how easy it is, but I decided to make it even easier! I wrote a function to write all the additional code for me to make my WPF window pop up. All I have to do is give it valid XAML code and let it do it’s magic!
Simply design a window in Visual Studio (the free version is fully featured to design WPF) and then copy and paste the XAML into the ISE as the variable $xaml. Here’s my sample XAML:
[xml]$xaml = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Name="Button" Content="Button" Width="100" Height="100"/> <Label Name="Label" Content="This is my label!" HorizontalAlignment="Left" VerticalAlignment="Top"/> </Grid> </Window> '@
Remember to remove the x:Class=”” bit from the first line. This is there to tell the compiler where the code behind the window is. In Powershell, we don’t have any code behind the XAML so this will cause the Window to error out. You can read more about x:Class here if you want to learn more!
Now that we have our XAML in a fresh Powershell window, run it! Why? The XAML variable needs to be loaded into the Powershell session for this function to work, so it needs to be run. If you have other code in the script you don’t want to load, highlight the XAML code and hit F8:
Now, simply run the function New-EphingWPFCode and it will create the variable $Window and write all the code you need to start! It will also add in the click events if it finds any Button or MenuItem controls.
New-EphingWPFCode -xaml $xaml
Hit Run and watch your new Window pop up! Add any code into the click event of the button and it will run when the button is clicked. The variables created are all $Window_NAME where Name is what they were called in the XAML. If you already have a Window variable and want a different name, you can specify the -VariableName switch to change it.
Let me know if you have any issues! Also, make sure you check out my run in a new window ISE extension to run scripts in a new Powershell window. WPF tends to make the ISE crash if you don’t do this.
Scroll to the bottom and click “View Raw” to get a nice copy/paste version of the code!