mvvmlight - 为视图模型选取url参数的"正确方法"是什么

Stu*_*art 4 windows-phone-7 mvvm-light

我只是将项目切换到mvvmlight并试图以"正确的方式"做事

我有一个带有列表框的简单应用程序

当在列表框中选择一个项目时,我已经连接了一个RelayCommand

此RelayCommand导致对INavigationService(http://geekswithblogs.net/lbugnion/archive/2011/01/06/navigation-in-a-wp7-application-with-mvvm-light.aspx)的调用,该调用导航到URL比如"/DetailPage.xaml?DetailId=12"

然后加载DetailPage.xaml并且......这是我有点不确定的地方......

  • 应该如何将DetailPage连接到DetailId为12的DetailView?
  • 我应该使用ViewLocator上的属性以某种方式在Xaml中执行此操作吗?
  • 我应该在NavigatedTo方法中这样做吗?

请随时给我一个完整的样本 - 确保这已经完成了一百次,但是所有的博客和教程似乎都在跳过这个最后的琐碎细节(而是集中在消息传递和on on on on on导航服务)

谢谢!

Cla*_*sen 5

您可以检索URL参数的唯一位置是在视图中.因此,由于您的视图可能取决于它,因此您应该在OnNavigatedTo方法中获取它.

然后,你应该将它传递给你的viewmodel,或者使用消息传递(如果你问我那么昂贵),或者通过引用你的datacontext(我认为是viewmodel),并在那里执行一个方法.

private AddTilePageViewModel ViewModel
{
    get
    {
        return DataContext as AddTilePageViewModel;
    }
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var postalCode = NavigationContext.TryGetKey("PostalCode");
    var country = NavigationContext.TryGetStringKey("Country");

    if (postalCode.HasValue && string.IsNullOrEmpty(country) == false)
    {
        ViewModel.LoadCity(postalCode.Value, country);
    }

    base.OnNavigatedTo(e);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用NavigationContext的一些特殊扩展来使它更容易.

namespace System.Windows.Navigation
{
    public static class NavigationExtensions
    {
        public static int? TryGetKey(this NavigationContext source, string key)
        {
            if (source.QueryString.ContainsKey(key))
            {
                string value = source.QueryString[key];

                int result = 0;
                if (int.TryParse(value, out result))
                {
                    return result;
                }
            }

            return null;
        }

        public static string TryGetStringKey(this NavigationContext source, string key)
        {
            if (source.QueryString.ContainsKey(key))
            {
                return source.QueryString[key];
            }

            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)