0

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.

hugo
  • 1,829
  • 1
  • 18
  • 47
  • 1
    Tell me, please what do you try to accomplish? Why do you need buttons and labels listen for collection changed? – Yehor Hromadskyi Sep 06 '17 at 07:12
  • 1
    @YehorHromadskyi Because some labels on the screen display information computed when the list of items is updated. And some buttons are disabled by commands (with CanExecute feature). Those CanExecute features relies also on the content of the list of items. – hugo Sep 06 '17 at 08:47
  • 1
    Your current method is the only option I'm aware of without creating some kind of "change cascade" framework that connects dependent objects together. – Bradley Uffner Sep 06 '17 at 11:45

1 Answers1

2

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).

martinstoeckli
  • 23,430
  • 6
  • 56
  • 87
  • That's what I did but in the CollectionChanged event of the collection. The resulting code should be the same if I understand what you mean. – hugo Sep 06 '17 at 11:39
  • @hugorgor - In your example you subscribe the `Collection.OnChange` event directly, of course this can be done. When subsrcibing to the `ViewModel.INotifyPropertyChanged.PropertyChanged` you would get informed, whenever your application does a notification, independend of whether the collection raised an event. The difference is subtle. – martinstoeckli Sep 06 '17 at 11:44