来自XML Findname问题的PowerShell WPF

时间:2011-04-29 08:29:20

标签: wpf powershell findname

我刚刚从here

测试了早期的PowerShell WPF示例
#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似乎在这里返回$ null。我发现一些帖子表明需要 RegisterName ,但我不知道如何在这里应用它。

1 个答案:

答案 0 :(得分:3)

据我所知,您的$ target是您的窗口。 你能尝试一下:

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

-------------编辑-------------

以下是使用FindName的代码我将Canvas替换为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