powershellicommand

Basic PowerShell XAML Button binding to ICommand


I have the following PowerShell script, which is nothing more than a XAML WPF GUI with a button that is supposed to show a MessageBox when clicked. It loads properly, but does nothing when clicked. What am I doing wrong?

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()

Solution

  • You'll want to bind the [VM] instance itself to Button.Command:

    <Button Width="100" Height="100" Content="Show" Command="{Binding}"/>
    

    ... and then fix the method invocation syntax in VM.Execute():

    [void]Execute([object]$arg){ $this.TryMethod() }