我对MVVM及其东西都是全新的。 你能帮我正确地将WPF按钮绑定到ICommand。
我正在绑定按钮:
<Button Command="{Binding OpenWindow}" >
在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
我将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构造函数部分中有一个例外,说“嵌套的sub没有与委托'Delegate Sub Action()'兼容的签名。我做错了什么?
答案 0 :(得分:1)
将其更改为:
OpenWindow = New RelayCommand(New Action(AddressOf ShowWindow))
RelayCommand
需要不带参数的操作。您的方法ShowWindow
也是一个没有参数的方法。但是您使用类型为Object
的一个参数声明了该操作。