Prism Sample 11-UsingDelegateCommands
本例的知识点,全在ViewModel中,看代码:
1 public class MainWindowViewModel : BindableBase 2 { 3 private bool _isEnabled; 4 public bool IsEnabled 5 { 6 get => _isEnabled; 7 set 8 { 9 SetProperty(ref _isEnabled, value); 10 ExecuteDelegateCommand.RaiseCanExecuteChanged(); 11 } 12 } 13 14 private string _updateText; 15 public string UpdateText 16 { 17 get => _updateText; 18 set => SetProperty(ref _updateText, value); 19 } 20 21 22 public DelegateCommand ExecuteDelegateCommand { get; private set; } 23 24 public DelegateCommand<string> ExecuteGenericDelegateCommand { get; private set; } 25 26 public DelegateCommand DelegateCommandObservesProperty { get; private set; } 27 28 public DelegateCommand DelegateCommandObservesCanExecute { get; private set; } 29 30 31 public MainWindowViewModel() 32 { 33 ExecuteDelegateCommand = new DelegateCommand(Execute, CanExecute); 34 35 DelegateCommandObservesProperty = new DelegateCommand(Execute, CanExecute).ObservesProperty(() => IsEnabled); 36 37 DelegateCommandObservesCanExecute = new DelegateCommand(Execute).ObservesCanExecute(() => IsEnabled); 38 39 ExecuteGenericDelegateCommand = new DelegateCommand<string>(ExecuteGeneric).ObservesCanExecute(() => IsEnabled); 40 } 41 42 private void Execute() 43 { 44 UpdateText = $"Updated: {DateTime.Now}"; 45 } 46 47 private void ExecuteGeneric(string parameter) 48 { 49 UpdateText = parameter; 50 } 51 52 private bool CanExecute() 53 { 54 return IsEnabled; 55 } 56 }
构造函数中建立了4个命令。
其中,33行这个是原始的,CanExecute要靠10行的代码来通知改变。后面的三个,是使用语法糖
ObservesCanExecute(() => IsEnabled)实现了自动通知。
这里可以试一下,注释掉
ExecuteDelegateCommand.RaiseCanExecuteChanged();然后运行的话,勾选Enabled,其他三个命令都改变状态,而第一个按钮就没有收到变更通知。
39行构造的命令为泛型命令,支持一个泛型的参数。参数在xaml中使用CommandParammeter提供。