Question

I'm totally new with MVVM and its stuff. Could you help me to correctly bind the WPF button to ICommand.

I'm binding the button:

<Button Command="{Binding OpenWindow}" >

In the ViewModel:

Public Sub New()
    OpenWindow = New RelayCommand(New Action(Of Object)(AddressOf ShowWindow))
End Sub

Private Sub ShowWindow()
    Dim win As New SecondWindow()
    win.Show()
End Sub

And I have the class RelayCommand as:

Public Class RelayCommand
    Implements ICommand

    Private ReadOnly _CanExecute As Func(Of Boolean)
    Private ReadOnly _Execute As Action

    Public Sub New(ByVal execute As Action)
        Me.New(execute, Nothing)
    End Sub

    Public Sub New(ByVal execute As Action, ByVal canExecute As Func(Of Boolean))
        If execute Is Nothing Then
            Throw New ArgumentNullException("execute")
        End If
        _Execute = execute
        _CanExecute = canExecute
    End Sub

    Public Custom Event CanExecuteChanged As EventHandler Implements System.Windows.Input.ICommand.CanExecuteChanged
        AddHandler(ByVal value As EventHandler)
            If _CanExecute IsNot Nothing Then
                AddHandler CommandManager.RequerySuggested, value
            End If
        End AddHandler

        RemoveHandler(ByVal value As EventHandler)
            If _CanExecute IsNot Nothing Then
                RemoveHandler CommandManager.RequerySuggested, value
            End If
        End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
            CommandManager.InvalidateRequerySuggested()
        End RaiseEvent
    End Event

    Public Function CanExecute(ByVal parameter As Object) As Boolean Implements System.Windows.Input.ICommand.CanExecute
        If _CanExecute Is Nothing Then
            Return True
        Else
            Return _CanExecute.Invoke
        End If
    End Function

    Public Sub Execute(ByVal parameter As Object) Implements System.Windows.Input.ICommand.Execute
        _Execute.Invoke()
    End Sub

End Class

With the above, I have an exception in the ViewModel constructor part saying "Nested sub does not have a signature that is compatible with delegate 'Delegate Sub Action()'. What am I doing wrong?

Was it helpful?

Solution

Change it to this:

OpenWindow = New RelayCommand(New Action(AddressOf ShowWindow))

The RelayCommand requires an action without parameters. Your method ShowWindow also is a method without parameters. But you declare the action with one parameter of type Object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top