Using MVVM, how to notify other properties and commands when a collection was modified

1.2k views Asked by At

In à program written in C# and Xamarin Forms (but this question is more based on MVVM), I have an ObservableCollection of Items:

        ObserbableCollection<Item> Items { get; set; }

When this collection changes (an item is added or removed to/from the collection), I need to notify other properties and commands because they are all binded to controls on a XAML screen (mostly buttons and labels).

The only solution I found was something like this:

        Items.CollectionChanged += (sender, args) =>
        {
            ((Command)OnHoldCommand).ChangeCanExecute();
            ((Command)CancelSaleCommand).ChangeCanExecute();
            ((Command)ValidateTakeAwayCommand).ChangeCanExecute();
            ((Command)ValidateEatInCommand).ChangeCanExecute();
            RaisePropertyChanged(() => TotalItems);
            RaisePropertyChanged(() => TotalAmount);
        };

Do you think there is another solution? Maybe using Fody.PropertyChanged?

I use FreshMvvm as Mvvm framework on top of Xamarin Forms.

1

There are 1 answers

2
martinstoeckli On BEST ANSWER

Your ViewModels usually implement the INotifyPropertyChanged interface. If it does, then you can subscribe to the PropertyChanged event and listen for changes of the collection, as the view would do. In the event handler, one can notify other properties if necessary.

Another more direct way is, when your ViewModel has control about inserts/changes, then you can notify other properties directly when e.g. the new item is inserted (calling the NotifyPropertyChanged() method).