我有以下 PowerShell 脚本,它只不过是一个 XAML WPF GUI,其中有一个按钮,单击该按钮时应该显示 MessageBox。它加载正确,但单击时不执行任何操作。我做错了什么?
Class VM : System.Windows.Input.ICommand {
add_CanExecuteChanged([EventHandler] $value) {
[System.Windows.Input.CommandManager]::add_RequerySuggested($value)
}
remove_CanExecuteChanged([EventHandler] $value) {
[System.Windows.Input.CommandManager]::remove_RequerySuggested($value)
}
[bool]CanExecute([object]$arg) { return $true; }
[void]Execute([object]$arg){ TryMethod }
[string] $Text = "Hello"
# Default constructor
VM() {
$this.Init(@{})
}
# Shared initializer method
[void] Init([hashtable]$Properties) {
foreach ($Property in $Properties.Keys) {
$this.$Property = $Properties.$Property
}
}
TryMethod() {
[System.Windows.MessageBox]::Show("Command Executed")
}
}
[string]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="400" Height="400">
<Grid>
<Label FontSize="48" Content="{Binding Text}" />
<Button Width="100" Height="100" Content="Show" Command="{Binding TryMethod}"/>
</Grid>
</Window>
"@
$Window = [Windows.Markup.XamlReader]::Parse($xaml)
$Window.DataContext = [VM]::New()
$Window.ShowDialog()
您需要将
[VM]
实例本身绑定到 Button.Command
:
<Button Width="100" Height="100" Content="Show" Command="{Binding}"/>
...然后修复
VM.Execute()
中的方法调用语法:
[void]Execute([object]$arg){ $this.TryMethod() }