Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 89864

ViewModel notification from collection item

$
0
0

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


Viewing all articles
Browse latest Browse all 89864

Trending Articles