Last active
October 9, 2021 20:01
-
-
Save nohwnd/2eca05a59caf52b517e85ae21a2a631d to your computer and use it in GitHub Desktop.
Weird WPF binding in PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This example shows three versions of behavior, in the first the data binding only | |
# picks up the property that is defined on the type, in the second it picks up ever | |
# powershell adapted property Name (alias property), and in the third it picks up | |
# all properties even though they are all powershell properties and not on the PSObjectType | |
# is there some special handling for PSObject regarding WPF in Windows PowerShell? | |
Add-Type -AssemblyName PresentationFramework | |
[string]$xaml = @" | |
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> | |
<StackPanel> | |
<Label Content="{Binding Name}" /> | |
<Label Content="{Binding Status}" /> | |
<Label Content="{Binding p.Name}" /> | |
<Label Content="{Binding p.Status}" /> | |
</StackPanel> | |
</Window> | |
"@ | |
[Diagnostics.PresentationTraceSources]::Refresh() | |
[Diagnostics.PresentationTraceSources]::DataBindingSource.Listeners.Add([Diagnostics.ConsoleTraceListener]::new()) | |
[Diagnostics.PresentationTraceSources]::DataBindingSource.Switch.Level = "Warning, Error" | |
$Window=[Windows.Markup.XamlReader]::Parse($xaml) | |
$vm = [PSCustomObject]@{ | |
p = (Get-Service | Select -First 1) | |
} | |
# just Status works because that is a ".net" property, | |
# but Name does not work because that is alias property | |
$Window.DataContext = $vm.p | |
# both Name and Status works for some reason, I am guessing | |
# that either some special property resolver is used for psobject | |
# that was provided by powershell, or it falls back to some other | |
# resolver for some different reason, like not having any ".net" | |
# properties, but I cannot find the real reason | |
$Window.DataContext = $vm | |
# works for all | |
$Window.DataContext = [PSCustomObject]@{ | |
p= [PSCustomObject]@{ | |
Name = 'name' | |
Status = 'running' | |
} | |
Name = 'name' | |
Status = 'running' | |
} | |
$Window.ShowDialog() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment