Xamarin Refresh Collection from ViewModel from another class

Issue

what is the best method to add/remove objects to a ObservableCollection in a ViewModel from another class in Xamarin.Forms?

Lets say I have a collection from type “Thing”. The Thing model contains name and description as a string.

Now I want to add a “Thing” object from another Page to this collection.

What is a way to do it?

Solution

The Xamarin.Forms MessagingCenter class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references. You can use MessagingCenter.Send to send object to the page and use MessagingCenter.Subscribe to receive it. Here is how I do in the new sample shell app:

DisplayPage:

     public partial class DisplayPage : ContentPage
        {
            public static ObservableCollection<People> mycol  new ObservableCollection<People>();
            public DisplayPage()
            {
                InitializeComponent();
                People p1  new People("Adam", 20);
                People p2  new People("Bob", 22);
                People p3  new People("Candy", 39);
                mycol.Add(p1);
                mycol.Add(p2);
                mycol.Add(p3);
                //recieve message
                MessagingCenter.Subscribe<OperatePage, People>(this, "message",  (sender, arg) >
                {
                    mycol.Add(arg);
                });
                col.ItemsSource  mycol;

            }
        }

SendObject:

  protected void onButtonClicked(Object sender, EventArgs e)
        {
            string name  inputname.Text;
            int age  Int16.Parse(inputage.Text);
            People newguy  new People(name,age);
            MessagingCenter.Send<OperatePage, People>(this, "message", newguy);

Results:

enter image description hereenter image description hereenter image description here

Answered By – Adrain Zhu -MSFT

Leave a Comment