为什么我的event.Subscribe()行返回空引用错误?

问题描述 投票:0回答:1

我正在和Caliburn Micro一起学习WPF。我已多次阅读文档,我甚至在Timcorey上关注YouTube的教程。在某个地方,我必须没有正确指定/初始化。

通常我会将对象指定为X obj = new X();但在这种情况下,eventaggregator不喜欢它。我确实设法通过将events.subscribe行更改为:来运行代码:

if (_events != null) _events.Subscribe(this)

但在运行时,即使设置了断点,代码也永远不会到达此行。删除所有eventaggregator代码后,我可以运行并触发我的事件。我似乎无法发布和订阅它。

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PropertyChanged;
using Caliburn.Micro;

using ERP101.EventModels;
using ERP101.ViewModels;

namespace ERP101.ViewModels
{
    [AddINotifyPropertyChangedInterface]
    public class ShellViewModel : Conductor<object>,IHandle<LoginEvent>
    {
        private IEventAggregator _events;
        private StartPageViewModel _startPVM;
        private SimpleContainer _container;

        public ShellViewModel(IEventAggregator events,StartPageViewModel startPVM,SimpleContainer container)
        {
            _events = events;
            _events.Subscribe(this); //null reference error here
            _startPVM = startPVM;
            _container = container;

             ActivateItem(_container.GetInstance<LoginViewModel>());

        }

        public void Handle(LoginEvent message)
        {
            ActivateItem(_startPVM);
        }
    }
}```

c# nullreferenceexception eventaggregator
1个回答
0
投票

谢谢艾米,所以我再次回到教程,我在容器代码中找到了我的问题。


        protected override void Configure()
        {
            _container.Instance(_container);
            _container
                .Singleton<IWindowManager, WindowManager>()
                .Singleton<IEventAggregator, EventAggregator>();

            GetType().Assembly.GetTypes()
                .Where(type => type.IsClass)
                .Where(type => type.Name.EndsWith("ViewModel"))
                .ToList()
                .ForEach(viewModelType => _container.RegisterPerRequest(viewModelType, viewModelType.ToString(), viewModelType));
        }

.Singleton<EventAggregator, EventAggregator>(); - 此行不正确,更正的行在上面的代码中。第一个必须是接口类型。

© www.soinside.com 2019 - 2024. All rights reserved.