kspearrin
kspearrin

Reputation: 10738

ViewModel PropertyChangedEventHandler null When Invoked From MessageCenter Subscription

In my ContentPage I subscribe with the MessageCenter waiting on an event to occur. When I receive that message I need to update my ViewModel that has a BindingContext to my ContentPage, like so:

Page

public class MyPage : ContentPage
{
    public MyPage()
    {
        Model = new ViewModel();

        MessagingCenter.Subscribe<Application>(Application.Current, "MyMessage", (sender) =>
        {
            Model.Activated = true;
        });

        // ...

        Title = "My Page";
        Content = stackLayout;
        BindingContext = Model;
    }

    public ViewModel Model { get; private set; }
}

View Model

public class ViewModel : INotifyPropertyChanged
{
    private bool _activated;
    public event PropertyChangedEventHandler PropertyChanged;

    public bool Activated
    {
        get { return _activated; }
        set
        {
            _activated = value;
            PropertyChanged(this, new PropertyChangedEventArgs(nameof(Activated)));
        }
    }
}

Whenever I try to set Model.Activated = true; from the message subscription, I get a null reference exception on the PropertyChangedEventHandler (PropertyChanged) in my ViewModel here:

PropertyChanged(this, new PropertyChangedEventArgs(nameof(Activated)));

I assume this is because the message center is running on a background thread or something.

How do I fix this?

Upvotes: 0

Views: 77

Answers (1)

Vinoth Rajendran
Vinoth Rajendran

Reputation: 1191

Move the bindingcontext assignment before Messagecenter function

Upvotes: 1

Related Questions