Monitoring sources for events in a M-V-VM world
Now Matteo wants that, each time a property exposed by the InnerViewModel changes, the command evaluation status is re-evaluated. As we said the solution is simple, just attach an handler to the PropertyChanged event of the InnerViewModel and re-evaluate the command.class InnerViewModel : INotifyPropertyChanged { } class OuterViewModel : INotifyPropertyChanged { public OuterViewModel() { //your own logic to setup the command and the inner view model } public InnerViewModel Inner{ get; set; } public ICommand DoSomething{ get; } }
So far…so good…with a lot a pollution around
Why pollution?
- The ICommand interface does not expose a method to request the command re-evaluation;
- You have to remember to attach the event on the inner view model and it is not natural because the focus, during development, is on the command not on the source of the change notification; this is the typical situation where you want a command to react to something that has happened…nothing more;
Let’s se what you can achieve using the Radical framework:
Or even easier using the brand new extension method:class OuterViewModel : INotifyPropertyChanged { public OuterViewModel() { //your own logic to setup the inner view model this.DoDomething = DelegateCommand.Create() .OnCanExecute( o => return true ) //your own validation logic .OnExecute( o => { } ) //your own execution logic .AddMonitor( PropertyObserver.ForAllPropertiesOf( this.InnerViewModel ); } public InnerViewModel Inner{ get; set; } public ICommand DoSomething{ get; } }
easy peasy lemon squeezy , implementing your own monitors is really straightforward, just implement the IMonitor interface or even easier inherit from the AbstractMonitor/AbstractMonitorclass OuterViewModel : INotifyPropertyChanged { public OuterViewModel() { //your own logic to setup the inner view model this.DoDomething = DelegateCommand.Create() .OnCanExecute( o => return true ) //your own validation logic .OnExecute( o => { } ) //your own execution logic .Observe( this.InnerViewModel ); } public InnerViewModel Inner{ get; set; } public ICommand DoSomething{ get; } }
Side notes:
- under the hood the DelegateCommand utilizes the weak event pattern;
- all the presented stuff is available for the full FX, for Silverlight 4 and for the Phone;
.m