Quick tip: XAML and named controls.

Last week I was working on a GUI tool that basically had to work without depending on ShowUI module being present on the box that I tend to use for most of GUI tools I built. I also wanted to use WPF, so I had to create it in XAML and just start from there. My main issue was: how do I get all named controls stored in variables without too much work on my side, something that ShowUI does automagically.

I could probably find some information online in many examples that already exist, but I decided to give it a try myself and eventually ended up with pretty simple code snippet that should work for any XAML defined GUI:

[xml]$XAML = @'
... XAML goes here ...

$Reader = New-Object System.Xml.XmlNodeReader $xaml             
$Dialog = [Windows.Markup.XamlReader]::Load($reader)            
foreach ($Name in (            
    $XAML |             
    Select-Xml '//*/@Name' |             
    foreach { $_.Node.Value}            
    )) {            
    New-Variable -Name "Control_$Name" -Value $Dialog.FindName($Name)            

Get-Variable Control_*

Because “Name” is just attribute of XML node with value that FindName method should be able to locate – in the end you get all your named controls stored in variables easy to find and handle:


This way I got ShowUI-feature ($Control_Name linked to named controls) pretty easily. And if I ever decide to change GUI and modify XAML – I won’t have to modify this code to get $Control_MyNewControl defined. Obviously, variable name can be simpler (in my production code I left ‘Control_’ prefix out). But still: I don’t have to touch this part of my code, just add some logic to my new control assuming variable related to it will be created for me and I’m good to go.


1 thought on “Quick tip: XAML and named controls.

  1. Pingback: GUI and PowerShell remoting | IT Pro PowerShell experience

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s