我正在开发 Windows Phone 7 应用程序。现在,我需要在用户点击指定按钮后切换 View ,将用户带到另一个 View 。
理论上,MVVM 中的哪个组件应该负责导航,即切换 View ?代码片段可以很好地展示演示。
我尝试在 View 中插入切换代码并且工作正常,但是我遇到了一种情况,我调用异步Web服务并且希望仅在操作完成后将用户导航到新 View ,导航代码应该位于事件处理程序内部。
谢谢。
P/S:我的项目截止日期快到了,我没有时间使用 MVVM 工具(例如 MVVM Light、Caliburn Micro 等)重建我的项目。
最佳答案
我在所有 ViewModel 共享的基类中放置了一个 Navigate 方法:
protected void Navigate(string address)
{
if (string.IsNullOrEmpty(address))
return;
Uri uri = new Uri(address, UriKind.Relative);
Debug.Assert(App.Current.RootVisual is PhoneApplicationFrame);
BeginInvoke(() =>
((PhoneApplicationFrame)App.Current.RootVisual).Navigate(uri));
}
protected void Navigate(string page, AppViewModel vm)
{
// this little bit adds the viewmodel to a static dictionary
// and then a reference to the key to the new page so that pages can
// be bound to arbitrary viewmodels based on runtime logic
string key = vm.GetHashCode().ToString();
ViewModelLocator.ViewModels[key] = vm;
Navigate(string.Format("{0}?vm={1}", page, key));
}
protected void GoBack()
{
var frame = (PhoneApplicationFrame)App.Current.RootVisual;
if (frame.CanGoBack)
frame.GoBack();
}
因此,如果您要求的话,ViewModel 基类将执行导航。然后,通常某些派生的 ViewModel 类会控制导航的目标,以响应绑定(bind)到 View 中的按钮或超链接的 ICommand 的执行。
protected SelectableItemViewModel(T item)
{
Item = item;
SelectItemCommand = new RelayCommand(SelectItem);
}
public T Item { get; private set; }
public RelayCommand SelectItemCommand { get; private set; }
protected override void SelectItem()
{
base.SelectItem();
Navigate(Item.DetailPageName, Item);
}
因此,View 只知道何时需要导航操作,而 ViewModel 知道去哪里(基于 ViewModel 和 Model 状态)以及如何到达那里。
关于c# - MVVM:哪个组件负责导航?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873850/