0

我对 MVVM 及其东西完全陌生。您能帮我正确地将 WPF 按钮绑定到 ICommand。

我正在绑定按钮:

<Button Command="{Binding OpenWindow}" >

在视图模型中:

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

我的 RelayCommand 类为:

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

有了上述情况,我在 ViewModel 构造函数部分有一个异常,说“嵌套子没有与委托'Delegate Sub Action()'兼容的签名。我做错了什么?

4

1 回答 1

1

将其更改为:

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

RelayCommand需要一个没有参数的动作。您的方法ShowWindow也是没有参数的方法。但是你用一个类型的参数来声明动作Object

于 2013-05-16T11:00:08.023 回答