我只是将一个项目切换到 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 ......这是我有点不确定的地方......
请随时向我指出一个完整的示例——确保这之前已经完成了(数百)次,但所有的博客和教程似乎都在跳过最后一个微不足道的细节(而是专注于消息传递和 ioc 上的导航服务)
谢谢!
最佳答案
您可以检索 URL 参数的唯一位置是在 View 中。因此,由于您的 View 可能依赖于它,您应该在 OnNavigatedTo 方法中获取它。
然后,您应该将它传递给您的 View 模型,或者使用消息传递(如果您问我的话,成本会很高),或者通过引用您的数据上下文(我认为是 View 模型),并在其上执行一个方法。
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);
}
我正在为 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;
}
}
}
关于windows-phone-7 - mvvmlight - 为 View 模型获取 url 参数的 "proper way"是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7079179/