Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Usage of messaging center in xamarin form

I’m currently trying to use Messaging Center to update the count of a shopping cart amount the message is sent with the correct data but is never received, and I’m not sure if my implementation is right (Never used it before) I’m trying to send data from a method to a view model to update a view from an Observable List Count here is my implementation

    public class Panier : BaseViewModel
    {
        private ObservableCollection<SmartDevice> content;

        public Panier()
        {
            this.content = new ObservableCollection<SmartDevice>();
        }

        public ObservableCollection<SmartDevice> GetContent() { return content; }

        public void AddProduct(SmartDevice product)
        {
            this.content.Add(product);
            int data = this.CountPanier();
            MessagingCenter.Send(this, "update counter", data);
        }

        public int CountPanier()
        {
            return this.content.Count;
        }

    }

Here is my View Model receiving the data

    internal class AppShellViewModel : BaseViewModel
    {
        private int counter = 0;
        public int Counter
        {
            get { return counter; }
            set 
            { 
                MessagingCenter.Subscribe<Panier, int>(this, "update counter", (x, data) =>
                {
                    counter = x.CountPanier();
                    OnPropertyChanged();
                });
            }
        }
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

first, you need to call Subscribe in your VM constructor, so that it will start listening for any incoming messages

MessagingCenter.Subscribe<Panier, int>(this, "update counter", (x) =>
   {
       Counter = x;
   });

then your send needs to use the same signature as the subscribe

MessagingCenter.Send<Panier,int>(this, "update counter", data);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading