CompositeCommandは、複数のコマンドをまとめて実行するためのクラスです。
CompositeCommandにあらかじめ ICommand を登録しておき、そのCompositeCommandが実行されると登録された全ての ICommand が実行される仕組みとなります。
例えばSaveAllのように、数多くの操作を蓄えてそれらを一気に実行させたい場合に利用します。
using Prism.Commands; using Prism.Mvvm; using System; namespace WpfPrismMvvm { public class MainWindowViewModel : BindableBase { private string _updatedText1; public string UpdateText1 { get { return _updatedText1; } set { SetProperty(ref _updatedText1, value); } } private string _updatedText2; public string UpdateText2 { get { return _updatedText2; } set { SetProperty(ref _updatedText2, value); } } public CompositeCommand CompositeButtonClickedCommand { get; } public DelegateCommand ButtonClickedCommand1 { get; private set; } public DelegateCommand ButtonClickedCommand2 { get; private set; } public MainWindowViewModel() { ButtonClickedCommand1 = new DelegateCommand(ButtonClickedProcess1); ButtonClickedCommand2 = new DelegateCommand(ButtonClickedProcess2); // CompositeCommandにDelegateCommandを登録する。 CompositeButtonClickedCommand = new CompositeCommand(); CompositeButtonClickedCommand.RegisterCommand(ButtonClickedCommand1); CompositeButtonClickedCommand.RegisterCommand(ButtonClickedCommand2); } private void ButtonClickedProcess1() { UpdateText1 = $"Updated: {DateTime.Now}"; System.Threading.Thread.Sleep(1000); } private void ButtonClickedProcess2() { UpdateText2 = $"Updated: {DateTime.Now}"; System.Threading.Thread.Sleep(1000); } } }
<Window x:Class="WpfPrismMvvm.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:prism="http://prismlibrary.com/" xmlns:l="clr-namespace:WpfPrismMvvm" mc:Ignorable="d" Title="MainWindow" Height="320" Width="480"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="1*" /> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <Button Command="{Binding CompositeButtonClickedCommand}" Content="CompositeCommand" Margin="10" Grid.Column="0" Grid.Row="0" /> <Button Command="{Binding ButtonClickedCommand1}" Content="ButtonClickedCommand1" Margin="10" Grid.Column="0" Grid.Row="1" /> <Button Command="{Binding ButtonClickedCommand2}" Content="ButtonClickedCommand2" Margin="10" Grid.Column="0" Grid.Row="2" /> <TextBlock Text="{Binding UpdateText1}" VerticalAlignment="Center" FontSize="14" Margin="10" Grid.Column="1" Grid.Row="1" /> <TextBlock Text="{Binding UpdateText2}" VerticalAlignment="Center" FontSize="14" Margin="10" Grid.Column="1" Grid.Row="2" /> </Grid> </Window>