【问题标题】:ViewModel PropertyChangedEventHandler null When Invoked From MessageCenter Subscription从 MessageCenter 订阅调用时 ViewModel PropertyChangedEventHandler null
【发布时间】:2016-07-03 03:21:14
【问题描述】:

在我的ContentPage 中,我订阅了MessageCenter 等待事件发生。当我收到该消息时,我需要将具有BindingContextViewModel 更新为我的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; 时,我的ViewModel 中的PropertyChangedEventHandler (PropertyChanged) 都会出现空引用异常:

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

我认为这是因为消息中心在后台线程或其他东西上运行。

我该如何解决这个问题?

【问题讨论】:

  • 在message.sub函数之前移动bindingcontext有什么区别
  • 哇,就是这样!发布为答案,我会接受。

标签: xamarin xamarin.forms


【解决方案1】:

将绑定上下文赋值移到消息中心函数之前

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2013-09-05
    相关资源
    最近更新 更多