复合命令
约 167 字小于 1 分钟
PrismC#MVVMWPF
2025-06-10
实现 IApplicationCommands:
public interface IApplicationCommands
{
CompositeCommand SaveAllCommand { get; }
}
public class ApplicationCommands : IApplicationCommands
{
public CompositeCommand SaveAllCommand { get; } = new CompositeCommand();
}在 ViewModel 中使用:
private IApplicationCommands _applicationCommands;
public IApplicationCommands ApplicationCommands
{
get { return _applicationCommands; }
set { SetProperty(ref _applicationCommands, value); }
}IApplicationCommands 需要通过 IoC 获取实例,可以在构造函数中注入。
在 View 中使用:
<Button Command="{Binding ApplicationCommands.SaveAllCommand}" Content="Save All"/>在 ViewModel 中注册命令:
ApplicationCommands.SaveAllCommand.RegisterCommand(SaveCommand);这个 SaveCommand 可以是一个 DelegateCommand,也可以是一个 CompositeCommand,这样可以实现多个命令的组合。当 SaveAllCommand 被执行时,所有注册的命令都会被执行。
Bootstrapper.cs:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IApplicationCommands, ApplicationCommands>();
}在 Bootstrapper.cs 中注册 IApplicationCommands。