PowerShell WPF从XML查找名称问题

brjng4g3  于 2023-04-22  发布在  Shell
关注(0)|答案(2)|浏览(139)

我刚刚测试了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,但我不知道,如何在这里应用这个。

lymgl2op

lymgl2op1#

据我所知,你的$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
mzillmmw

mzillmmw2#

只要给予你的窗口一个“x:Name”:

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

相关问题