我有一个 Silverlight 4 项目,它显示一个图表和一些按钮,允许用户更改图表的日期范围。日期范围也可以通过查询字符串参数传入 - 例如 http://myserver/MySilverlightPage/#?DateRange=OneMonth - 当用户单击一个按钮时,我也想更新 URL。
我知道这样做的方法是调用 this.NavigationService.Navigate(new Uri(...))
,但据我所知,这只能从 Silverlight 页面代码后面完成。由于我使用的是 MVVM,因此命令的所有处理都在 ViewModel 类中进行。有没有办法调用Navigate
或以其他方式从 ViewModel 中更改 URL?
澄清一下,xaml 包括以下 Button
:
<Button Content="1 Month View"
Command="{Binding OneMonthCommand}" />
ViewModel 类包含一个
OneMonthCommand
属性(property):public ICommand OneMonthCommand { get; set; }
单击按钮时,我的 ICommand 实现的
Execute
方法被调用。问题是 - 我如何从该方法中更改 URL?
最佳答案
我发现这是我使用 MVVM 模式编写的 Silverlight 应用程序中的一个常见问题。我使用 NavigationHelper 类来集中围绕导航的逻辑。它看起来像这样:
public interface INavigationHelper
{
void Home();
void SomeOtherPage();
}
public class NavigationHelper : INavigationHelper
{
private NavigationService _navSvc;
public NavigationHelper(NavigationService navSvc)
{
_navSvc = navSvc;
}
public void Home()
{
_navSvc.Navigate(new Uri("/Home", UriKind.Relative));
}
public void SomeOtherPage()
{
_navSvc.Navigate(new Uri("/SomeOtherPage", UriKind.Relative));
}
}
然后,我让 ViewModel 有一个 NavigationHelper 属性,该属性是在构造 ViewModel 时由页面设置的。
顺便说一句,在 ViewModel 的构造函数中传递 NavigationHelper 似乎会更简单。但是,根据我的经验,为 ViewModel 使用非默认构造函数会使在 Blend 中的设计时工作变得更加困难。
关于silverlight - 有没有办法从 ViewModel 中调用 Navigate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3729316/