I have a very basic powershell script that loads a xaml layout. It is throwing this error:
Exception calling "Load" with "1" argument(s):
"cannot create instance of 'Window' defined in
assembly 'PresentationFramework, Version=3.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
The calling thread must be STA, because many UI components require this. "
I've gone over the script and xaml files several times, but I'm not seeing where the problem is, and it doesn't help that I don't fully understand what the error I'm getting means either. Any help would be much appreciated. Thank You.
Powershell script:
Add-Type -AssemblyName presentationframework
$xaml = [xml](Get-Content MainWindow.xaml)
$reader = New-Object System.Xml.XmlNodeReader $xaml
$form = [Windows.Markup.XamlReader]::Load($reader)
$button = $form.FindName('testButton')
$button.Add_Click({
$s = $form.FindName('testBox').Text;
$form.FindName('testLabel').Content = $s;
})
$form.ShowDialog()
Xaml file:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Grid x:Name="LayoutRoot">
<TextBox x:Name="testBox" HorizontalAlignment="Left"
Margin="26.782,48.626,0,0" TextWrapping="Wrap"
Text="New label text" VerticalAlignment="Top" Width="130.22"/>
<Label x:Name="testLabel" Content="User Search" HorizontalAlignment="Left"
Margin="20.666,22.666,0,0" VerticalAlignment="Top"/>
<Button x:Name="testButton" Content="Change It!" HorizontalAlignment="Left"
Margin="26.782,85,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
This error is what I call the "because I said so error", and it means exactly what it says.
You can't load XAML in Powershell.exe because it's STA. And "many" components require this. My many, I mean WPF.
Luckily, every PowerShell host supports STA
There are much easier ways to write UI in PowerShell though. You should check out showui.codeplex.com.
Hope this helps,
@BrandonRisell, check out ShowUI a PowerShell module to help build WPF user interfaces in script.
ShowUI makes the complicated world of WPF easy to use in PowerShell. You can use ShowUI to write simple WPF gadgets, quick front ends for your scripts, components, and full applications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With