Handling button clicks using MVPVM and Event Aggregation

by Administrator 17. December 2011 10:57

There are many ways button clicks can be handled with WPF.  My preference is to minimize the amount of time spent having to wire up my buttons so that I can focus on the required business logic.   By allowing the framework to handle button clicks I can also provide a consistent means for handling them, i.e., for the http://SolrContrib.CodePlex.com project you merely have to look to the Presenter's OnCommandExecute() method for any button click within the application.

All I am required to do is create the button as shown in the following SecurityView.xaml code and place my code in the corresponding Presenter, in this case the SecurityPresenter:

I can get away with this because my solutions Resource\Gwn.Resource.xxxx (where xxxx is Desktop or Silverlight) has the following declaration for TargetType Button:


Note: both the Desktop and Silverlight applications are sharing the same file (not linked) [read more]:

Note above on line 4 that we bind our command to the ViewModel's EventAggregatorCommand - this command is in the ViewModelBase (available to all view models) and is wired up as shown below in lines 69 thru 104:

With the above noted wire-up in the ViewModelBase all applicable buttons will publish an event for both CanExecute and Execute - the ViewModelBase packages up the applicable payload information and raises a system ProcessEvent.

In the image above we see where the PresenterBase subscribes to the ProcessEvent (lines 85/86) - when a ProcessEvent is raised it will be handled by EventAggregatorSet (which really should be called ProcessEventHandler so I'll be refactoring this...).   Based on the type of event, ModulesLoaded or EventAggregatorCommand it will call the applicable process.   In the case of our EventAggregatorCommand it will call OnCommandEvent() shown below:

The above process handles more than just button Execute and CanExecute - note that on lines 152-155 that we are determining if a particular view should be visible (each presenter listens for button events and will set itself visible/collapse as applicable).

Since the base will only allow Presenters to handle their own ViewModel events, and XAML will not permit us to have two controls with the same name, we can safely use the button name within a switch statement to handle the button click as shown below: 

Examining the image above we can see that within a few minutes work all I am required to do is create my view, go to the presenter and apply the business logic without any additional work for the wire up of button click events; I can focus on business requirements.