目的
复合命令可以触发多个与之注册的命令,可以实现一次执行多个命令。可以实现类似全部保存这种业务需求。
实现
1、创建ICompositeCommands接口和CompositeCommands实现类
将Prism中提供的CompositeCommand对象进行包装,包装为ICompositeCommands接口和ApplicationCommands实现类
public interface IApplicationCommands
{
CompositeCommand SaveCommand { get; }
}
public class ApplicationCommands : IApplicationCommands
{
private CompositeCommand _saveCommand = new CompositeCommand();
public CompositeCommand SaveCommand
{
get { return _saveCommand; }
}
}
2、IOC中注册复合命令
在App.xaml后台代码中进行IOC注册
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IApplicationCommands, ApplicationCommands>();
}
3、ViewModel中定义复合命令
在ViewModel中定义复合命令,并将该命令绑定到View层
ViewModel:
private IApplicationCommands _applicationCommands;
public IApplicationCommands ApplicationCommands
{
get { return _applicationCommands; }
set { SetProperty(ref _applicationCommands, value); }
}
public MainWindowViewModel(IApplicationCommands applicationCommands)
{
ApplicationCommands = applicationCommands;
}
View:
<Button Content="Save" Margin="10" Command="{Binding ApplicationCommands.SaveCommand}"/>
4、将其他多个地方的Command注册该复合命令
public TabViewModel(IApplicationCommands applicationCommands)
{
_applicationCommands = applicationCommands;
UpdateCommand = new DelegateCommand(Update).ObservesCanExecute(() => CanUpdate);
_applicationCommands.SaveCommand.RegisterCommand(UpdateCommand);
}
private void Update()
{
UpdateText = $"Updated: {DateTime.Now}";
}
这样当触发复合命令 ApplicationCommands.SaveCommand时,所有注册的命令都会触发。