Raise CanExecuteChanged on model change

In mine ViewModel

I have ObservableCollection

objects Person

(which implement INotifyPropertyChanged

) and a property SelectedPerson

. They are bound to the ListBox in my opinion.

The following Prism DelegateCommel is also present 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 to call MyCommand.RaiseCanExecuteChanged if it SelectedPerson

changes and when the age changes SelectedPerson

?

Adding and removing properties changed by handlers in the installer SelectedPerson

seems a little messy to me.

+3


source to share


1 answer


Adding and removing properties changed by handlers in SetTorcher SelectedPerson seems a bit messy to me.

This is how I do it, and I'm not sure what a cleaner alternative would be. If the state of the command depends on a sub-property, you need to observe the changes in some way. However, be careful about unsubscribing or you risk a memory leak if yours Person

outlives your view model. PropertyChangedEventManager

and weak event handlers can help if you cannot guarantee that you will unsubscribe.



To keep things clean, I usually only have one handler that listens for any sub-property changes, which calls a method RequeryCommands

(also called directly via viewmodel methods), which in turn calls RaiseCanExecuteChanged

for everyone in my opinion.

+1


source







All Articles