Thursday, July 15, 2010

Silverlight: Auto Notifying Delegate Commands

Prism provides Delegate Command equivalent to WPF's Delegate Command (ICommand) implementation in Silverlight. Using Delegate Command in Silverlight you can bind Commands to your view.
Whenever state of command changes, you will be doing something like this:

MyDelegateCmd.RaiseCanExecuteChanged()

which will notify binding system to requery binded command's CanExecute. In above approach your code will be scattered with RaiseCanExecteChanged across application. Instead you can use following class which will auto notify binding system.

public class AutoDelegateCommand<T> : DelegateCommand<T>
{

public INotifyPropertyChanged ViewModel { get; set; }
private void ListenForPropertyChagnedEventAndRequery(INotifyPropertyChanged presentationModel)
{
if (presentationModel != null)
{

presentationModel.PropertyChanged += (sender, args) =>
{
QueryCanExecute(args);
};
}
}

public void QueryCanExecute(PropertyChangedEventArgs args)
{
this.RaiseCanExecuteChanged();
}
}
public AutoDelegateCommand(INotifyPropertyChanged PresentationModel, Action executeMethod)
: base(executeMethod)
{
this.ViewModel = PresentationModel;
ListenForPropertyChagnedEventAndRequery(PresentationModel);
}
public AutoDelegateCommand(INotifyPropertyChanged PresentationModel, Action executeMethod, Func canExecuteMethod)
: base(executeMethod, canExecuteMethod)
{
this.ViewModel = PresentationModel;
ListenForPropertyChagnedEventAndRequery(PresentationModel);
}

}

By using above delegate command there will be no need to call requery in your view model. AutoDelegateCommand will subscribe to PropertyChanged event of passed in view model, and for each property change event it will raise RaiseCanExecute event.

No comments: