3

In my ViewModel I have an ObservableCollection of Person objects (that implement INotifyPropertyChanged) and a SelectedPerson property. These are bound to a ListBox in my view.

There is also the following Prism DelegateCommand in my ViewModel:

Private DelegateCommand _myCommand = New DelegateCommand(CanExecute)
Public DelegateCommand MyCommand {get {return _myCommand;}}

Private Bool CanExecute()
{
    Return (SelectedPerson.Age > 40);
}

What is the most elegant way of calling MyCommand.RaiseCanExecuteChanged whenever the SelectedPerson changes and whenever the SelectedPerson's age changes?

Adding and removing property changed handlers in the SelectedPerson's setter seems a bit messy to me.

Kurren
  • 760
  • 7
  • 18

1 Answers1

1

Adding and removing property changed handlers in the SelectedPerson's setter seems a bit messy to me.

That's how I do it, and I'm not sure what a cleaner alternative would be. If the command state depends on a sub-property, you need to observe the changes somehow. Be careful about unsubscribing, though, or you risk a memory leak if your Person outlives your view model. PropertyChangedEventManager and weak event handlers can help if you can't guarantee that you unsubscribe.

To keep things clean, I usually just have one handler that listens for any sub-property changes, which calls a RequeryCommands method (also called directly by view model methods), which in turn invokes RaiseCanExecuteChanged for all the commands in my view.

Mike Strobel
  • 23,622
  • 51
  • 65