c# - MVVM:哪个组件负责导航?

标签 c# asp.net windows-phone-7 mvvm

我正在开发 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/

相关文章:

c# - 如何格式化数字以具有相同的位数?

c# - LINQ 子查询、分组依据和计数

asp.net - 使用 EntityReference 查询时出现问题

c# - ASP.NET MailMessage.BodyEncoding 和 MailMessage.SubjectEncoding 默认值

c# - 我们可以使用asp.net网站上传到youtube的最大视频大小是多少

css - jQuery Mobile,将样式应用于 Windows Phone 上的动态内容(芒果)

c# - LINQ 查询以创建从字符串集合组合的对象集合

c# - 如何将文件添加到 Azurite [Azure 存储模拟器]

windows-phone-7 - Windows Phone 7 麦克风可以检测 18k-19kHz 范围内的频率吗?

windows-phone-7 - 在 Wp7 中将重力与加速度分开(仅使用加速度 Api)