I'm在WP7工作application.-嵌套MVVM與定位
摘要
我要顯示一個頁面(1)好友列表,如果有朋友被竊聽i'll秀一個頁面(2)與這個朋友信息加上這個朋友看過的電影列表。然後,如果我點擊一個電影,我將獲得一個帶有電影信息的頁面(3)。我正嘗試在MVVM Light Toolkit中使用MVVM模式。
服務:
在每一頁上,我需要打個電話給API
第1頁:/friend
返回好友列表
第2頁:/friend/5436
返回此觀看電影朋友
第3頁:/movie/87968
返回關於電影
我做什麼
信息10我創建具有電影的的ObservableCollection
public class Friend: ObservableObject
{
public Friend(){}
public ObservableCollection<Movie> Movies{ get; set; }
}
還要創建一個電影類電影的資訊朋友類。
另外一個視圖模型來包裝朋友類
public class FriendViewModel : ViewModelBase
{
public Friend Model
{
get;
private set;
}
public FriendViewModel(Friend model)
{
Model = model
}
}
然後一個視圖模型讓所有的朋友
public class FriendListViewModel : ViewModelBase
{
// To store the Friend service returned by the locator
private readonly IFriendService _friendService;
// To store the friends. It should be bind the the listbox in the view
public ObservableCollection<FriendViewModel> Friends
{
get;
private set;
}
/// <summary>
/// Initializes a new instance of the FriendListViewModel class.
/// </summary>
public FriendListViewModel(IFriendService friendService)
{
// The data service
_friendService = friendService;
// Get all the friends and add them to the Friends collection
Friends = new ObservableCollection<FriendViewModel>();
_friendService.GetFriends((result, error) =>
{
if (error != null)
{
MessageBox.Show(error.Message);
return;
}
if (result == null)
{
MessageBox.Show("Nothing found");
return;
}
foreach (var friend in friends)
{
Friends.Add(new FriendViewModel(friend));
}
});
}
}
每一件事的工作與定位是在App靜態資源。 xaml和在視圖中使用的我列出朋友作爲視圖的datacontext
這是定位器
public class FriendViewModelLocator
{
static FriendViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IFriendService, Design.DesignFriendDataService>();
}
else
{
SimpleIoc.Default.Register<IFriendService, FriendService>();
}
SimpleIoc.Default.Register<FriendListViewModel>();
}
/// <summary>
/// Gets the Main property.
/// </summary>
public FriendListViewModel FriendList
{
get
{
return ServiceLocator.Current.GetInstance<FriendListViewModel>();
}
}
}
問題
第一頁工作,我得到的朋友列表,我可以顯示它們。第一頁也是可混合的。但是我不知道如何繼續下一頁。我以爲我應該通過相同的FriendViewModel
我點擊頁面2並調用api來獲取電影列表。但是在某些方面,它被朋友模式拋棄,我無法填寫Friend上的Movies集合。我應該爲每個頁面創建不同的視圖模型包裝器。如何配置定位器能夠獲得電影和電影信息的頁面3.
任何想法,想法,資源檢查?
我讀了yout blogpost,我不太明白模型如何在_「場景」_中扮演它的角色,我有這樣的想法,即你沒有模型,但模式是MVVM .. – blackjid 2012-02-05 14:19:48
The視圖模型與您的服務層交互以檢索模型實例。無論如何,視圖和視圖模型交互都是相同的。 – ColinE 2012-02-05 14:28:50
@blackjid在博客文章中,我鏈接到模型是從Twitter搜索返回的XML數據。 – ColinE 2012-02-05 14:42:14