PowerShell WPF from XML Findname Problem

2.4k views Asked by At

I just tested an early PowerShell WPF example from here

#requires -version 2

Add-Type -AssemblyName PresentationFramework

[xml] $xaml = @"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="408">
    <Canvas>
        <Button x:Name="button1"
          Width="75"
          Height="23"
          Canvas.Left="118"
          Canvas.Top="10"
          Content="Click Here" />
    </Canvas>
</Window>
"@

$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$target=[Windows.Markup.XamlReader]::Load($reader)

$window= $target.FindName("Window")
$control=$target.FindName("button1")

$eventMethod=$control."add_click"
$eventMethod.Invoke({$window.Title="Hello $((Get-Date).ToString('G'))"})

$target.ShowDialog() | out-null

FindName seems to return $null here. I found some posts indicating, that RegisterName is needed, but I have no idea, how to apply this here.

2

There are 2 answers

1
JPBlanc On BEST ANSWER

As far as I understand your $target is your window. Can you try :

Clear-Host
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
[System.Windows.Window]$Window=[Windows.Markup.XamlReader]::Load($reader)
$Window.Title = "Bonjour"
$controls=$Window.Content
[System.Windows.Controls.Button]$Button = ($controls.Children)[0]
$eventMethod=$Button.add_Click
$eventMethod.Invoke({$window.Title="Hello $((Get-Date).ToString('G'))"})
$Window.ShowDialog() | out-null

------------- EDIT -------------

Here is the code working with FindName I replace Canvas by Grid :

#requires -version 2
Add-Type -AssemblyName PresentationFramework
[xml]$xaml = 
@"
<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="300" Width="408">
    <Grid>
      <Button x:Name="button1"
                Width="75"
                Height="23"
                Canvas.Left="118"
                Canvas.Top="10"
                Content="Click Here" />
    </Grid>
</Window>
"@

Clear-Host
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$target=[Windows.Markup.XamlReader]::Load($reader)
$control=$target.FindName("button1")
$eventMethod=$control.add_click
$eventMethod.Invoke({$target.Title="Hello $((Get-Date).ToString('G'))"})
$target.ShowDialog() | out-null 
0
D'Artagnan On

Just give a "x:Name" to your window:

<Window x:Name = "Window" ...