Technology Sharing

WPF Prism Framework Composite Commands

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Purpose

A compound command can trigger multiple commands registered with it, and can execute multiple commands at a time. It can also meet business requirements such as saving all.

accomplish

1. Create ICompositeCommands interface and CompositeCommands implementation class

Wrap the CompositeCommand object provided in Prism into an ICompositeCommands interface and ApplicationCommands implementation class

 public interface IApplicationCommands
    {
        CompositeCommand SaveCommand { get; }
    }

    public class ApplicationCommands : IApplicationCommands
    {
        private CompositeCommand _saveCommand = new CompositeCommand();
        public CompositeCommand SaveCommand
        {
            get { return _saveCommand; }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2. Registering compound commands in IOC
Register IOC in the App.xaml code behind

 protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
   containerRegistry.RegisterSingleton<IApplicationCommands, ApplicationCommands>();
}
  • 1
  • 2
  • 3
  • 4

3. Define composite commands in ViewModel
Define the composite command in the ViewModel and bind the command to the View layer
ViewModel:

  private IApplicationCommands _applicationCommands;
        public IApplicationCommands ApplicationCommands
        {
            get { return _applicationCommands; }
            set { SetProperty(ref _applicationCommands, value); }
        }

        public MainWindowViewModel(IApplicationCommands applicationCommands)
        {
            ApplicationCommands = applicationCommands;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

View:

 <Button Content="Save" Margin="10" Command="{Binding ApplicationCommands.SaveCommand}"/>
  • 1

4. Register the compound command in multiple other places

 public TabViewModel(IApplicationCommands applicationCommands)
  {
    _applicationCommands = applicationCommands;

    UpdateCommand = new DelegateCommand(Update).ObservesCanExecute(() => CanUpdate);

    _applicationCommands.SaveCommand.RegisterCommand(UpdateCommand);
}
 
private void Update()
{
  UpdateText = $"Updated: {DateTime.Now}";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

In this way, when the composite command ApplicationCommands.SaveCommand is triggered, all registered commands will be triggered.