内在观点的倚赖

时间:2016-07-09 19:02:19

标签: xamarin prism

如何在内部ViewModel中解析我的依赖项?

我创建页面xaml页面“p1”并添加内部内容视图“p2”      

然后,我创建了p2ViewMovel并且这项工作。但是当我在p2ViewMovel中添加一个依赖“IEventAggregator”并获得null引用异常时。

我做错了什么?

/Views/p1.xaml

<?xml version="1.0" encoding="utf-8"?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             xmlns:views="clr-namespace:Tests.Views;assembly=Tests.Shell"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="Tests.Views.p1">
    <StackLayout>
        <views:p2 />
    </StackLayout>
</ContentPage>

/Views/p2.xaml

<?xml version="1.0" encoding="utf-8"?>

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="Tests.Views.p2">
    <Label Text="{Binding Text}" />
</ContentView>

/ViewModels/p1ViewModel.cs

public class p1ViewModel : BindableBase, INavigationAware {
    private readonly IEventAggregator _eventAggregator;

    public p1ViewModel(IEventAggregator eventAggregator) {
        _eventAggregator = eventAggregator;
    }

    public void OnNavigatedFrom(NavigationParameters parameters) {}

    public void OnNavigatedTo(NavigationParameters parameters) {
        _eventAggregator.GetEvent<t>().Publish("p1");
    }
}

/ViewModels/p2ViewModel.cs

public class p2ViewModel : BindableBase {
    private readonly IEventAggregator _eventAggregator;
    private string _text = "p2";

    public p2ViewModel(IEventAggregator eventAggregator) {
        _eventAggregator = eventAggregator;
        _eventAggregator.GetEvent<t>().Subscribe(s => Text = s);

    }

    public string Text {
        get { return _text; }
        set { SetProperty(ref _text, value); }
    }
}

/PubSubEvents/t.cs

public class t : PubSubEvent<string> {}

如果我删除

public p2ViewModel(IEventAggregator eventAggregator) {
    _eventAggregator = eventAggregator;
    _eventAggregator.GetEvent<t>().Subscribe(s => Text = s);
}

一切正常

1 个答案:

答案 0 :(得分:0)

问题在这里ViewModelLocationProvider.cs。 Prism不使用DI容器作为默认值。或者UnityBootstrapper.cs。 Prism无法通过容器解析内部ViewModel并使用Activator.CreateInstance

我的问题通过直接注册解决了

ViewModelLocationProvider.Register<p2>(() => Container.Resolve<p2ViewModel>());

对于支持导航,我添加了注册

Container.RegisterType<INavigationService, UnityPageNavigationService>( new ContainerControlledLifetimeManager());

不知道为什么UnityBootstrapper不这样做。