我刚刚从这里测试了一个早期的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是需要的,但我不知道,如何在这里应用。
据我所知,您的$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
------------- EDIT -------------
下面是使用FindName
的代码,我用Grid
代替Canvas
:
#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
给出一个"x:Name"到你的窗口:
<Window x:Name = "Window" ...