2015-10-07 73 views
1

我使用簡單的噴油器創建IoC容器。我把這裏的模式:簡單的噴油器 - 註冊集合

Page Navigation using MVVM in Store App

當我問到上面的帖子評論,我想註冊INavigationPage的集合。我做了這樣的:

private static void RegisterNavigationPages() 
{ 
     Container.RegisterCollection<INavigationPage>(new [] 
     { 
      typeof(MainNavigationPage), 
      typeof(SecondNavigationPage) 
     }); 
} 

容器我的ViewModels和的NavigationService到裏面:

Container.Register<INavigationService, NavigationService>(Lifestyle.Singleton); 
Container.Register<IMainViewModel, MainViewModel>(Lifestyle.Singleton); 
Container.Register<ISecondViewModel, SecondViewModel>(Lifestyle.Singleton); 

這是這樣,我怎麼設置頁面的DataContext:

DataContext = App.Container.GetInstance<IMainViewModel>(); 

一切都OK但我想在ViewModel構造函數中使用該集合中的NavigationPages。我可以通過索引做到這一點:

public SecondViewModel(INavigationService navigationService, IEnumerable<INavigationPage> navigationPageCollection) 
{ 
    NavigationService = navigationService; 
    _navigationPage = (navigationPageCollection.ToList())[0]; 
    GoToMainPageCommand = new Command(GoToMainPageAction); 
} 

但它並不是完美的解決方案,因爲當我改變NavigationPages的順序我將不得不改變所有索引在整個應用程序。當我能夠識別哪個NavigationPage我想在ViewModel構造函數中使用時,它是否有任何解決方案?

我不能通過typeof來實現,因爲NavigationPage類型在UIProject中,而且我無法從ViewModel項目中獲取引用,因爲存在循環引用依賴關係。

+0

所以'SecondViewModel'只需要與MainNavigationPage一起工作,還是需要更多的導航頁面迭代呢? – Steven

+0

現在只有該頁面,但在未來可能會需要更多的分頁。幾個不同的頁面可以有幾個按鈕。它只是應用程序的骨架。目標是約10頁與查看模型。 – darson1991

回答

4

目前SecondViewModel的正確性完全取決於navigationPageCollection的順序和填充情況,這使得它非常脆弱。如果你的SecondViewModel需要MainNavigationPage,這就是你應該注入的。不要注入一個集合;注入頁面本身。這可能意味着MainNavigationPage需要自己的接口,例如IMainNavigationPage。這消除了您現在正在使用的任何歧義。但是,如果不是負載一對一映射非通用接口(違反了RAP principle),則可以更好地定義few generic abstractions

+1

實際上,OP鏈接到一個SO問題,其中示例代碼提供了一個NavigationPage 。將T從那裏定義的抽象類移動到接口將解決問題。 –

+0

不是很直接,因爲我不能在ViewModel中注入它,因爲我不能使用頁面類型,所以我不能在構造函數參數中這樣做: INavigationPage mainNavigationPage。 – darson1991

0

我有一個類似的問題,並已解決此問題之前。在這裏閱讀我的博客 clean factory pattern

基本上你需要添加一個方法或屬性來標識INavigationPage中的用戶,然後在SecondViewModel中添加相同的標識符。 SecondViewModel構造函數只需遍歷IEnumerable並找到它所需的頁面。

相關問題