2016-07-09 8 views
0

内部ViewModelの依存関係をどのように解決できますか?内部ビューの依存関係

私は、ページのXAMLページ "P1" を作成し、内部contentview "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); 
} 

すべてはうまく

+0

質問を編集してコードを入力してください。エラーが発生している場所を示します。これは私たちがあなたを助けるのに役立ちます。 –

+0

ビューモデルをどのように作成しますか? 'new'を使って自分で作成する場合は、依存関係を渡す必要があります。つまり、サブオブジェクトの依存関係は所有オブジェクトの依存関係になります。 – Haukinger

+0

ViewModelによって作成された 'prism:ViewModelLocator.AutowireViewModel =" xamlのTrue "' – Lailore

答えて

0

問題がここにViewModelLocationProvider.csた作品。プリズムはデフォルトでDIコンテナを使用しません。またはここにUnityBootstrapper.cs。 Prismはなぜ知らない私は、登録

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

を追加するコンテナで、内側のViewModelを解決し、私の問題は、直接registarionによって支援ナビゲーションのための

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

を解決したActivator.CreateInstance

を使用することはできませんUnityBootstrapperはそれをしません。

+0

あなたはどのバージョンのプリズムを使用していますか? –

関連する問題