ViewModel notification from collection item

ArmandCharbonnierArmandCharbonnier FRMember ✭✭
edited October 2015 in Xamarin.Forms

Hi everyone,

I'm using Xamarin.Forms and MVVMLight for an Mobile application.

I've got a ViewModel which contains a collection of ObservableObject.

I'm not using a listview because i can't for business purpose. I was wondering if it's possible through NotifyPropertyChanged or something to Notify my ViewModel when i'm setting a Value on one of the ObservableObject.

I tryied to handle the CollectionChangedEvent but it's only raised when i delete / add an item in the collection. I'm not moving any item in the collection, just modify them.

Here is a sample code for what i'm trying to do :

public class MyCollectionItem : ObservableObject 
    {
        public string Value
        {
            get { return _value; }
            set { Set(() => Value, ref _value, value); }
        }
    }

    public class MyViewModel : ViewModelBase
    {
        private ObservableCollection<MyCollectionItem> _myCollection;
        public ObservableCollection<MyCollectionItem> MyCollection
        {
            get { return _myCollection; }
            set { Set(() => MyCollection, ref _myCollection, value); }
        }

        public MyViewModel()
        {
            MyCollection = new ObservableCollection<MyCollectionItem>();
            // Getting items and fill collection
        }
    }

    public class MyPage : ContentPage
    {
        private MyViewModel ViewModel;

        public MyPage()
        {
            BindingContext = ViewModel = new MyViewModel();

            StackLayout container = new StackLayout();
            foreach(var item in ViewModel.MyCollection)
            {
                var entry = new Entry();
                entry.BindingContext = item;
                entry.SetBinding(Entry.TextProperty, "Value");
                container.Children.Add(entry);
            }
        }
    }

The idea here is i'm adding an entry in the Page for each item in the ViewModel collection. When i set a text in the entry, i want the MyCollectionItem to notify the ViewModel that his Value property changed.

I've got a working solution at the moment, using message with MvvmLight Messenger system, but i don't know if it's the right way to do it. (I send a message to the ViewModel when the Set() method on the Value property succeeded).

Thanks !

Armand

Best Answer

Answers

  • Hi and thanks adamkemp,

    The solution was in front of me but i couldn't see it. You gave me the right lead :)

    How do I set a post answered ?

    Thanks,

Sign In or Register to comment.