从MessageCenter订阅调用时,ViewModel PropertyChangedEventHandler为null

时间:2016-07-02 18:48:57

标签: xamarin xamarin.forms

在我的ContentPage我订阅MessageCenter等待事件发生。当我收到该消息时,我需要将ViewModel的{​​{1}}更新为BindingContext,如下所示:

ContentPage

查看模型

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; }
}

每当我尝试从消息订阅中设置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))); } } } 时,我的Model.Activated = true; PropertyChangedEventHandlerPropertyChanged)上的空引用异常就会出现:

ViewModel

我认为这是因为消息中心正在后台线程上运行。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

在Messagecenter函数

之前移动bindingcontext赋值