在我的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;
PropertyChangedEventHandler
(PropertyChanged
)上的空引用异常就会出现:
ViewModel
我认为这是因为消息中心正在后台线程上运行。
我该如何解决这个问题?
答案 0 :(得分:1)
在Messagecenter函数
之前移动bindingcontext赋值