本文介绍了Container.Resolve< IEventAggregator>()上的棱镜null异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Resources.Add("eventAggregator",Container.Resolve())行;引发Null异常.

The line Resources.Add("eventAggregator", Container.Resolve()); raises Null exception.

更新我添加了所有类以解释更多信息.就像@Axemasta所说的那样,不需要注册IEventAggregator,并且我删除了注册.现在,我不介绍如何将Listview EventAggregator行为连接到EventAggregator.

UPDATEI've added all classes to explain more. As @Axemasta said, there is no need to register IEventAggregator and I removed registration. Now I don't how to connect the Listview EventAggregator behavior to the EventAggregator.

这是整个App.xaml代码文件.

This is whole App.xaml code file.

public partial class App : PrismApplication
{
    /*
     * The Xamarin Forms XAML Previewer in Visual Studio uses System.Activator.CreateInstance.
     * This imposes a limitation in which the App class must have a default constructor.
     * App(IPlatformInitializer initializer = null) cannot be handled by the Activator.
     */
    public App() : this(null) { }


    public App(IPlatformInitializer initializer) : base(initializer) { }

    protected override async void OnInitialized()
    {
        InitializeComponent();

        Resources.Add("eventAggregator", Container.Resolve<IEventAggregator>());// Removed on update

        FlowListView.Init();

        await NavigationService.NavigateAsync("NavigationPage/MainPage");

    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation<NavigationPage>();
        containerRegistry.RegisterForNavigation<MainPage>();
    }
}

}

行为类:

public class ScrollToMyModelBehavior : BehaviorBase<ListView>
{
    private IEventAggregator _eventAggregator;
    public IEventAggregator EventAggregator
    {
        get => _eventAggregator;
        set
        {
            if (!EqualityComparer<IEventAggregator>.Default.Equals(_eventAggregator, value))
            {
                _eventAggregator = value;
                _eventAggregator.GetEvent<ScrollToMyModelEvent>().Subscribe(OnScrollToEventPublished);
            }
        }
    }

    private void OnScrollToEventPublished(ListItem model)
    {
        AssociatedObject.ScrollTo(model, ScrollToPosition.Start, true);
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
        base.OnDetachingFrom(bindable);
        // The Event Aggregator uses weak references so forgetting to do this
        // shouldn't create a problem, but it is a better practice.
        EventAggregator.GetEvent<ScrollToMyModelEvent>().Unsubscribe(OnScrollToEventPublished);
    }
}

事件类:

public class ScrollToMyModelEvent : PubSubEvent<ListItem>
{
}

页面浏览模型:

        public MainPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator)
        : base (navigationService)
    {
        Title = "صفحه اصلی";
        ListHeight = 100;
        ListWidth = 250;

        _eventAggregator = eventAggregator;

        Items items = new Items();
        ListViewItemSouce = items.GetItems();

        MyModels = items.GetItems();
        SelectedModel = ListViewItemSouce[3];
        _eventAggregator.GetEvent<ScrollToMyModelEvent>().Publish(SelectedModel);
    }

页面浏览量:

<StackLayout HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="{Binding ListWidth}" HeightRequest="{Binding ListHeight}"
                         Grid.Row="1" Grid.Column="1">
                <local:NativeListView x:Name="lst3" ItemsSource="{Binding ListViewItemSouce}" Margin="1" BackgroundColor="Transparent" RowHeight="47" HasUnevenRows="false">
                    <ListView.Behaviors>
                        <local:ScrollToMyModelBehavior EventAggregator="{StaticResource eventAggregator}" /> // Error raised that there is not such a static property
                    </ListView.Behaviors>
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextCell Text="{Binding Word}"  TextColor="Black"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </local:NativeListView>
            </StackLayout>

推荐答案

应用初始化时,无需注册IEventAggregator,就像INavigationServiceIPageDialog一样,您可以直接使用它!

You do not need to register IEventAggregator when the app initialises, much like INavigationService or IPageDialog, you can use it straight out of the box!

要使用EventAggregator,您应该执行以下操作:

To use EventAggregator you should do the following things:

创建活动

您首先需要创建一个事件(使用棱镜),您可以将其传递给EventAggregator.您的事件应继承自PubSubEvent,您可以向其传递一个对象(可选).因此,您的活动将如下所示:

You will first need to create an Event (using Prism) that you can pass to the EventAggregator. Your event should inherit from PubSubEvent, you can pass this an object (optional). So your event would look like this:

using System;
using Prism.Events;

namespace Company.App.Namespace.Events
{
    public class SampleEvent : PubSubEvent
    {
    }
}

看看最近使用的应用程序,我最常在自定义弹出视图之间传递数据(例如参数字典)时使用它.

Looking at a recent app, I most commonly use this when passing data between custom popup views (like a dictionary of params).

订阅活动

在触发IEventAggregator时,已预订该事件的所有对象都将执行指定的任何代码.在您要接收该事件的班级中,您必须执行以下操作:

When IEventAggregator fires, anything that has subscribe to the event will execute any code specified. In the class you want to recieved the event you will have to do the following:

  • 将类IEventAggregator通过构造函数传递(棱镜将最终由DI进行处理)
  • 初始化本地IEventAggregator以便在此类中使用
  • IEventAggregator订阅处理程序方法.
  • Pass the class IEventAggregator through the constructor (prism does the DI afterall)
  • Initialise a local IEventAggregator for use in this class
  • Subscribe IEventAggregator to a handler method.

代码如下所示:

public class TheClassListeningForAnEvent
{
    private readonly IEventAggregator _eventAggregator;

    public TheClassListeningForAnEvent(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
        _eventAggregator.GetEvent<SampleEvent>().Subscribe(OnEventRecieved);
    }

    void OnEventRecieved()
    {
        //Do something here
    }
}

触发事件

现在您已经注册了该活动,您可以触发该活动.将IEventAggregator传递到您要触发事件的任何类中,然后使用Publish Method:

Now you have registered for the event, you can fire the event. Pass the IEventAggregator into whatever class you want to fire the event from and use the Publish Method:

public class TheClassPublishingAnEvent
{
    private readonly IEventAggregator _eventAggregator;

    public TheClassListeningForAnEvent(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;

        _eventAggregator.GetEvent<SampleEvent>().Publish();
    }
}

这就是它的长短.您可以将任何内容传递给IEventAggregator,只需要使用您所订购的方法来处理即可.

Thats the long and the short of it. You could pass anything to the IEventAggregator, you would just need to handle for this in the methods you are subscribing.

希望这足以让您使用IEventAggregator

这篇关于Container.Resolve&lt; IEventAggregator&gt;()上的棱镜null异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:55
查看更多