如果通过视图将命令编组到视图模型,则可以从视图模型控制 CanExecute。我一直在多个 Caliburn 项目中使用这种方法。可能不像使用 Interactivity 那样“光滑”,但 CanExecute 有效。
<UserControl x:Class="MyView"
...
Name="View"
>
<UserControl.InputBindings>
<KeyBinding Key="F5"
Command="{Binding RefreshCommand, ElementName=View, Mode=OneWay}" />
</UserControl.InputBindings>
<Button Command="{Binding Path=RefreshCommand, ElementName=View, Mode=OneWay}"/>
在您的 View 类中,您将命令连接到 MyView.DataContext 属性中引用的 View Model。
Class MyView
Public Property RefreshCommand As _
New RelayCommand(AddressOf Refresh,
Function()
If ViewModel Is Nothing Then
Return False
Else
Return ViewModel.CanRefresh
End If
End Function)
Private Sub Refresh()
ViewModel.Refresh()
End Sub
Private ReadOnly Property ViewModel As MyViewModel
Get
Return DirectCast(DataContext, MyViewModel)
End Get
End Property
End Class