who subscribes to the ICommand.CanExecuteChanged event?

I put a breakpoint on the event add{} and found out exactly which object is subscribing to the ICommand.CanExecuteChanged event.

 

————— wpf_proj_readme.txt —————–

This entire wpf app has a single VM. Among other things it defines a bool method vm.CanExecuteSave(). Note VM isn’t subclass of ICommand; TanBinRelayCommand is. It’s just a generic relay command class.

 

Xaml has a textbox and a Save button. Textbox is data-bound to a string property in VM; button to an ICommand property in VM – consistency. Entire xaml uses the VM as the only data context, so all data bindings are between the xaml (visuals) and the VM (properties) – consistency.

 

This vm.CanExecuteSave() method (wrapped in a delegate) is passed in when instantiating TanBinRelayCommand, the Command object behind the button. Therefore button “dimmer” is connected to vm.CanExecuteSave() method. Later at runtime the button is dimmed when CanExecuteSave becomes false.

———————————————————–

 

Question is how does the runtime know when to requery CanExecuteSave(). The solution, as a standard pattern, is event subscription. Specifically, the button adds this.OnCanExecuteChanged() method into the inv list of the ICommand.CanExecuteChanged event.   But when is this method added into the inv list? At xaml initialization, HookCommand() performs this registration.

 

    abstract public class TanBinRelayCommand: ICommand{

        private Action methodToExecute;

        private Func<bool> isEnabled;

 

        public TanBinRelayCommand(Action methodToExecute, Func<bool> isEnabled)

        {

            this.methodToExecute = methodToExecute;

            this.isEnabled = isEnabled;

        }

        #region ICommand members

        ///

        /// who subscribes to this event? I think the command binding (or other objects in the xaml)

        ///

        bool ICommand.CanExecute(object obj) {

            if (this.isEnabled == null) return true;

           

            return this.isEnabled.Invoke();

        }

        void ICommand.Execute(object obj)

        {

            if (this.methodToExecute != null)

                this.methodToExecute.Invoke();

        }

        abstract public event EventHandler CanExecuteChanged;

       

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s