UWP. How to pass command-parameter when ItemClickCommand of AdaptiveGridView executes? - c#

<uwpkit:AdaptiveGridView ItemsSource="{x:Bind ViewModel.FavoriteContacts}"
IsItemClickEnabled="True"
SelectedItem="{x:Bind ViewModel.SelectedContact,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ItemClickCommand="{x:Bind ViewModel.ExecuteCommand}">
</uwpkit:AdaptiveGridView>
This AdaptiveGridView show list of favorite contacts and instead of handling event ItemClick I choosed to use command. Furthermore I need to pass selected contact as command parametr. So I have found ItemClickCommand property that can help me use command. But I have not found any way that will allow me pass command parameter.
I tried to solve this problem with creating property SelectedContact and bind it to SelectedItem property of AdaptiveGridView but barrier that don't allow me to use this scenario is that execution of command runs before SelectedContact setter accessor runs. And I have null reference exception thrown.
So it was my only idea how to solve this task. If you know how to solve this task or maybe how to change order of executions of command and setter accessor of SelectedItem explain this.

First of all, It’s not very clear about “This AdaptiveGridView show list of favorite contacts and instead of handling event ItemClick I choosed to use command”. Does it mean “show list of favorite contacts” is only the itemsSource or when you handle ItemClick event, “the list of favorite contacts” will change?
But about “pass selected contact as command parameter”,you can read the following code:
First,in XAML:
<uwpkit:AdaptiveGridView ItemsSource="{x:Bind ViewModel.FavoriteContacts}"
IsItemClickEnabled="True"
ItemClickCommand="{x:Bind ViewModel. ExecuteCommand}">
Next,you can create command class like this:
public class RelayCommand : ICommand
{
public Contact selectedContact;
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(object parameter)
{
selectedContact = parameter as Contact;
_execute();
}
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Then,in your ViewModel,you can Initialize the command class as a property:
public RelayCommand ExecuteCommand { get; set; }
,this property is binded to “ItemClickCommand” in XAML.Also,you can initialize the ExecuteCommand and pass the MyItemClick event to the command:
public ContactViewModel() { ExecuteCommand = new RelayCommand(MyItemClick); }
in your ViewModel’s constructor.
Last,you can see the command has a “public void Execute(object parameter)” method . It has one parameter, which can be used to pass the information binded with the UIElement from the caller to the command. It means when you click the item,it will be triggered and the “Contact” object will be passed by this method.Then you can save it.So,when you click the item,the “MyItemClick” method will be triggered and you can use the Contact object you saved in the Execute method,for example:
private void MyItemClick(){
Contact contact = ExecuteCommand.selectedContact;
//do something when clicked
}
If you still have the problem, please share more details about your code, like a reproduce-able demo.

Related

Delegate Command - WPF Button Binding Not Working [duplicate]

I'm having some difficulty with Context Menu commands on my View Model.
I'm implementing the ICommand interface for each command within the View Model, then creating a ContextMenu within the resources of the View (MainWindow), and using a CommandReference from the MVVMToolkit to access the current DataContext (ViewModel) Commands.
When I debug the application, it appears that the CanExecute method on the command is not being called except at the creation of the window, therefore my Context MenuItems are not being enabled or disabled as I would have expected.
I've cooked up a simple sample (attached here) which is indicative of my actual application and summarised below. Any help would be greatly appreciated!
This is the ViewModel
namespace WpfCommandTest
{
public class MainWindowViewModel
{
private List<string> data = new List<string>{ "One", "Two", "Three" };
// This is to simplify this example - normally we would link to
// Domain Model properties
public List<string> TestData
{
get { return data; }
set { data = value; }
}
// Bound Property for listview
public string SelectedItem { get; set; }
// Command to execute
public ICommand DisplayValue { get; private set; }
public MainWindowViewModel()
{
DisplayValue = new DisplayValueCommand(this);
}
}
}
The DisplayValueCommand is such:
public class DisplayValueCommand : ICommand
{
private MainWindowViewModel viewModel;
public DisplayValueCommand(MainWindowViewModel viewModel)
{
this.viewModel = viewModel;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (viewModel.SelectedItem != null)
{
return viewModel.SelectedItem.Length == 3;
}
else return false;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show(viewModel.SelectedItem);
}
#endregion
}
And finally, the view is defined in Xaml:
<Window x:Class="WpfCommandTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCommandTest"
xmlns:mvvmtk="clr-namespace:MVVMToolkit"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<mvvmtk:CommandReference x:Key="showMessageCommandReference" Command="{Binding DisplayValue}" />
<ContextMenu x:Key="listContextMenu">
<MenuItem Header="Show MessageBox" Command="{StaticResource showMessageCommandReference}"/>
</ContextMenu>
</Window.Resources>
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding TestData}" ContextMenu="{StaticResource listContextMenu}"
SelectedItem="{Binding SelectedItem}" />
</Grid>
</Window>
To complete Will's answer, here's a "standard" implementation of the CanExecuteChanged event :
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
(from Josh Smith's RelayCommand class)
By the way, you should probably consider using RelayCommand or DelegateCommand : you'll quickly get tired of creating new command classes for each and every command of you ViewModels...
You have to keep track of when the status of CanExecute has changed and fire the ICommand.CanExecuteChanged event.
Also, you might find that it doesn't always work, and in these cases a call to CommandManager.InvalidateRequerySuggested() is required to kick the command manager in the ass.
If you find that this takes too long, check out the answer to this question.
Thank you for the speedy replies. This approach does work if you are binding the commands to a standard Button in the Window (which has access to the View Model via its DataContext), for example; CanExecute is shown to be called quite frequently when using the CommandManager as you suggest on ICommand implementing classes or by using RelayCommand and DelegateCommand.
However, binding the same commands via a CommandReference in the ContextMenu
do not act in the same way.
In order for the same behaviour, I must also include the EventHandler from Josh Smith's RelayCommand, within CommandReference, but in doing so I must comment out some code from within the OnCommandChanged Method. I'm not entirely sure why it is there, perhaps it is preventing event memory leaks (at a guess!)?
public class CommandReference : Freezable, ICommand
{
public CommandReference()
{
// Blank
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (Command != null)
return Command.CanExecute(parameter);
return false;
}
public void Execute(object parameter)
{
Command.Execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandReference commandReference = d as CommandReference;
ICommand oldCommand = e.OldValue as ICommand;
ICommand newCommand = e.NewValue as ICommand;
//if (oldCommand != null)
//{
// oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
//}
//if (newCommand != null)
//{
// newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
//}
}
#endregion
#region Freezable
protected override Freezable CreateInstanceCore()
{
throw new NotImplementedException();
}
#endregion
}
However, binding the same commands via a CommandReference in the
ContextMenu do not act in the same way.
That's a bug in CommandReference implementation. It follows from these two points:
It is recommended that the implementers of ICommand.CanExecuteChanged hold only weak references to the handlers (see this answer).
Consumers of ICommand.CanExecuteChanged should expect (1) and hence should hold strong references to the handlers they register with ICommand.CanExecuteChanged
The common implementations of RelayCommand and DelegateCommand abide by (1). The CommandReference implementation doesn't abide by (2) when it subscribes to newCommand.CanExecuteChanged. So the handler object is collected and after that CommandReference no longer gets any notifications that it was counting on.
The fix is to hold a strong ref to the handler in CommandReference:
private EventHandler _commandCanExecuteChangedHandler;
public event EventHandler CanExecuteChanged;
...
if (oldCommand != null)
{
oldCommand.CanExecuteChanged -= commandReference._commandCanExecuteChangedHandler;
}
if (newCommand != null)
{
commandReference._commandCanExecuteChangedHandler = commandReference.Command_CanExecuteChanged;
newCommand.CanExecuteChanged += commandReference._commandCanExecuteChangedHandler;
}
...
private void Command_CanExecuteChanged(object sender, EventArgs e)
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, e);
}
In order for the same behaviour, I must also include the EventHandler
from Josh Smith's RelayCommand, within CommandReference, but in doing
so I must comment out some code from within the OnCommandChanged
Method. I'm not entirely sure why it is there, perhaps it is
preventing event memory leaks (at a guess!)?
Note that your approach of forwarding subscription to CommandManager.RequerySuggested also eliminates the bug (there's no more unreferenced handler to begin with), but it handicaps the CommandReference functionality. The command with which CommandReference is associated is free to raise CanExecuteChanged directly (instead of relying on CommandManager to issue a requery request), but this event would be swallowed and never reach the command source bound to the CommandReference. This should also answer your question as to why CommandReference is implemented by subscribing to newCommand.CanExecuteChanged.
UPDATE: submitted an issue on CodePlex
An easier solution for me, was to set the CommandTarget on the MenuItem.
<MenuItem Header="Cut" Command="Cut" CommandTarget="
{Binding Path=PlacementTarget,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}"/>
More info: http://www.wpftutorial.net/RoutedCommandsInContextMenu.html

Implementing a custom WPF Command

I wanted to implement a custom WPF command and I searched and found the following code:
public static class CustomCommands
{
public static readonly RoutedUICommand Exit = new RoutedUICommand
(
"Exit",
"Exit",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.F4, ModifierKeys.Alt)
}
);
//Define more commands here, just like the one above
}
There are two things that I can't figure out.
Is it necessary to have commands static readonly? Cant we just declare it using const?
What exactly new InputGestureCollection() { new KeyGesture(Key.F4, ModifierKeys.Alt) } is? If it is calling default constructor and initializing properties so there should be a property to be assigned to, but there is nothing to be assigned. InputGestureCollection has braces, but inside braces it is not initialing any properties. How? What is this type of statement?
First of all, you need to get some basic understanding of WPF with MVVM.
You have a class that you are going to bind to your UI. That class is not the .xaml.cs
It is completely independent of the View. You need to put an instance of the class into the DataContext of the Window you can do this in the .xaml.cs by calling sth like that:
this.DataContext = new MyViewModel();
Now your class MyViewModel needs a Property of type ICommand.
Best practice is to make a class that implements ICommand. Normally you call it DelegateCommand or RelayCommand.
Example:
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
Then in your ViewModel you create a property with an Instance of that class in it. Like that:
public class MyViewModel{
public DelegateCommand AddFolderCommand { get; set; }
public MyViewModel(ExplorerViewModel explorer)
{
AddFolderCommand = new DelegateCommand(ExecuteAddFolderCommand, (x) => true);
}
public void ExecuteAddFolderCommand(object param)
{
MessageBox.Show("this will be executed on button click later");
}
}
In your view you can now bind the command of a button to that property.
<Button Content="MyTestButton" Command="{Binding AddFolderCommand}" />
A routed command is something that already exists in the framework by default (copy, paste etc). If you're a beginner to MVVM you shouldn't be thinking of creating routed commands before you get the basic understanding of "normal" commands.
To answer your first question: It is absolutely not nessesary to make Commands static and/or const. (See class MyViewModel)
Your 2nd question: You can initialize Lists with default values that you put into the {-brackets.
Example:
var Foo = new List<string>(){ "Asdf", "Asdf2"};
You don't have a object you initialize properties of. You have a list you initialize and then the Add() is called with the parameters you put in the {-brackets.
That's what basicly happens in your case too. You have a collection that you initialize with some values.
To answer your second question:
new InputGestureCollection()
{
new KeyGesture(Key.F4, ModifierKeys.Alt)
}
This is an example of a collection initializer and is equivalent to:
var collection = new InputGestureCollection();
collection.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
It's just a shorthand, and something that ReSharper suggests.

WPF Simple Commanding Example

I try not to post questions like this, but i've really been struggling to find an answer or similar example. I have what I think is a really simple example I'd like to setup.
Basically I want to use commanding to add an item from a textbox to a listbox. I want to make sure there is something in the textbox via CanExecute and i want to make sure that its not already in the list.
I know this seems over complicated for what it is, but it hits on some points I've been struggling with.
<Window x:Class="Commanding_Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:Commanding_Example"
Title="MainWindow" Width="200" Height="300">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<StackPanel>
<TextBlock>Name</TextBlock>
<TextBox></TextBox>
<Button>Add</Button>
<Button>Remove</Button>
<ListBox ItemsSource="{Binding People}" DisplayMemberPath="Name"></ListBox>
</StackPanel>
</Window>
I have a Person Class
class Person
{
public string Name { get; set; }
}
The only reason I have this is that the Add needs to create a new object, so slightly more complex than a simple string.
And then a basic view model
class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
People = new ObservableCollection<Person>();
People.Add( new Person {Name = "jimmy"});
}
public ObservableCollection<Person> People { get; set; }
#region Default INotifyPropertyChanged implimentation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
So the question is, how would I implement commanding so that it uses the CanExecute to disable the Add button if the name is already there or the Name field is empty.
And then the same deal for Remove, only enabled if a name is selected in the list.
I'd like to make this as MVVM compliment as possible.
I've seen that you can do the Button.CommandBindings attached property to inject the methods you'd like to use for each, but that doesnt seem completely MVVM happy.
Also, i'd like to avoid the use of frameworks (Prism/Caliburn.Micro) since this is primarily for education reasons.
Also any references would be greatly appreciated. I've read many blogs etc but I always feel like they stray off before implementing a complete, simple example.
how would I implement commanding so that it uses the CanExecute to
disable the Add button if the name is already there or the Name field
is empty
I will show how to do the add, the remove is similar and I leave that for you to figure out. First I will show the xaml changes with the button using an AddPerson command:
<TextBox Text="{Binding CurrentPerson,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged
}"/>
<Button Command="{Binding AddPerson}">Add</Button>
We have bound the current edited text to a new property on the View Model named CurrentPerson. This is done because we want to access what the person enters, but also we need the binding updated as the user types. To accomplish that updating, we specify that the binding updates by setting the UpdateSourceTrigger attribute to be PropertyChanged. Otherwise our the CurrentPerson string and ultimately the command Can operation would only fire when the edit text box lost focus.
ViewModel
The viewmodel will subscribe to the AddPerson command. Execution of that will add the user, but also check a can method which returns a boolean whether to enable the button or not. The can will be excecuted when the CurrentPerson property changes where we ultimately call RaiseCanExecuteChanged on the commanding class to have the button check the can method.
(This VM is abbreviated for the example and based on your full VM)
public OperationCommand AddPerson { get; set; }
public string _currentPerson;
public MainViewModel()
{
People = new ObservableCollection<Person>();
People.Add(new Person { Name = "jimmy" });
// First Lamda is where we execute the command to add,
// The second lamda is the `Can` method to enable the button.
AddPerson = new OperationCommand((o) => People.Add(new Person { Name = CurrentPerson }),
(o) => (!string.IsNullOrWhiteSpace(CurrentPerson) &&
!People.Any(per => per.Name == CurrentPerson)));
// When the edit box text changes force a `Can` check.
this.PropertyChanged += MainViewModel_PropertyChanged ;
}
void MainViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentPerson")
AddPerson.RaiseCanExecuteChanged();
}
Finally here is the commanding class used which is based on my blog article Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding.:
public class OperationCommand : ICommand
{
#region Variables
Func<object, bool> canExecute;
Action<object> executeAction;
public event EventHandler CanExecuteChanged;
#endregion
#region Properties
#endregion
#region Construction/Initialization
public OperationCommand(Action<object> executeAction)
: this(executeAction, null)
{
}
public OperationCommand(Action<object> executeAction, Func<object, bool> canExecute)
{
if (executeAction == null)
{
throw new ArgumentNullException("Execute Action was null for ICommanding Operation.");
}
this.executeAction = executeAction;
this.canExecute = canExecute;
}
#endregion
#region Methods
public bool CanExecute(object parameter)
{
bool result = true;
Func<object, bool> canExecuteHandler = this.canExecute;
if (canExecuteHandler != null)
{
result = canExecuteHandler(parameter);
}
return result;
}
public void RaiseCanExecuteChanged()
{
EventHandler handler = this.CanExecuteChanged;
if (handler != null)
{
handler(this, new EventArgs());
}
}
public void Execute(object parameter)
{
this.executeAction(parameter);
}
#endregion
}
Well, MVVM is just a pattern or philosophy, so I think your desire to avoid using a framework might be a little misguided. Even if you're not using one of those frameworks, you will essentially be writing your own framework in order to implement the MVVM pattern.
That being said, probably what you want to use is a DelegateCommand or one of the similar implementations. See: http://www.wpftutorial.net/DelegateCommand.html. The important part that I think you are looking for is that the command that the WPF button is binding to must raise the CanExecuteChanged event whenever there is a change made in the view model which affects whether the command can or cannot be executed.
So in your case, for example, you would want to add a call to the CanExecuteChanged of your AddPersonDelegateCommand to your OnPropertyChanged method (possibly filtered by the name of the property that was changed). This tells anything bound to the command to call CanExecute on the command, and then you would have your logic in that CanExecute that actually determines if a person with the entered name already exists.
So to add some sample code, it might look something like this:
class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
People = new ObservableCollection<Person>();
People.Add( new Person {Name = "jimmy"});
AddPersonDelegateCommand = new DelegateCommand(AddPerson, CanAddPerson);
}
// Your existing code here
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if(propertyName == "NewNameTextBox") AddPersonDelegateCommand.RaiseCanExecuteChanged();
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public DelegateCommand AddPersonDelegateCommand { get; set; }
public void AddPerson()
{
// Code to add a person to the collection
}
public bool CanAddPerson()
{
return !People.Any(p=>p.Name == NewNameTextBox);
}
public string NewNameTextBox
{
get { return _newNameTextBox; }
set
{
_newNameTextBox = value;
OnPropertyChanged();
}
}
}
*Note: In this sample your <TextBox></TextBox> would need to be bound to the NewNameTextBox property on the view model.

Setting Property in Data Context from Action/Command

I have a DataTrigger in my XAML which is binded to a Property, 'ShowEffect' in my ViewModel class. I also have a button which is binded to a RelayCommand (class shown below) that calls a method. In that method, I set 'ShowEffect' to true. However, the DataTrigger does not seem to respond; the effect is not shown:
I declare the Property using:
private Boolean _ShowEffect;
public Boolean ShowEffect
{
get { return _ShowEffect; }
set { _ShowEffect = value; }
}
RelayCommand Class:
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
}
I'm wondering whether the issue is related to the dispatcher. Can anyone suggest why the binding isn't working when I set the property in the method called by the command? It works when I set the property anywhere else in the ViewModel.
Converting previous comment to an answer.
your VM needs to implement INPC if it doesn't already and ShowEffect needs to Raise the propertychanged handler when it's changed(from it's setter when value changes) for changes made to it to be recognized by the View. What you got right now is a simple property which will not notify view of any updates made to it which is prolly what's happening when the command changes it's value but the view never gets to know about the change and your DataTrigger seems to not work.
INotifyPropertyChanged interface is what informs the View a property in the VM has changed. Hence your property needs to raise the PropertyChanged handler for it to thereby inform the view of any changes made to it.

Can I call a command inside a command?

I have a closecommand defined inside my viewmodel for my dialog window. I have another command defined inside that viewmodel. Now I have that command binded to a control in my view. After performing certain command actions, I want it to call closecommand to close the window. Is that possible?
Yes. You can use a CompositeCommand that wraps both (or any number) of your other commands. I believe this is in Prism, but if you don't have access to that in your project, it isn't terribly difficult to implement similar functionality on your own, especially if you're not using parameters - all you do is implement ICommand with a class and then have a private List of ICommands inside the class.
Here's more on the CompositeCommand class from Prism:
http://msdn.microsoft.com/en-us/library/microsoft.practices.composite.presentation.commands.compositecommand_members.aspx
My own admittedly short and possibly non-canonical implementation follows. To use it, all you need to do is have this be referenced on your VM, and then bind to it instead. You can call .AddCommand for all the other commands that you want to run. Probably the Prism one is implemented differently, but I believe this will work:
public class CompositeCommand : ICommand {
private List<ICommand> subCommands;
public CompositeCommand()
{
subCommands = new List<ICommand>();
}
public bool CanExecute(object parameter)
{
foreach (ICommand command in subCommands)
{
if (!command.CanExecute(parameter))
{
return false;
}
}
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
foreach (ICommand command in subCommands)
{
command.Execute(parameter);
}
}
public void AddCommand(ICommand command)
{
if (command == null)
throw new ArgumentNullException("Yadayada, command is null. Don't pass null commands.");
subCommands.Add(command);
}
}

Categories