我开始在应用程序中实现MVVM,但在知道用户何时导航到视图时遇到了问题。
要在视图之间导航,我只需使用navigationService.Navigate(...);
导航到视图时如何检查?我可以使用事件navigationService.Navigated
吗?
页面本身是否提供了像OnNavigatedTo这样的其他方法?
XAML:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP71"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
DataContext="{Binding titleSearchViewModel, Source={StaticResource Locator}}">
<i:Interaction.Triggers>
<i:EventTrigger>
<cmd:EventToCommand Command="{Binding PageLoaded, Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
VM:
private RelayCommand _PageLoaded;
public RelayCommand PageLoaded
{
get
{
if (_PageLoaded == null)
{
_PageLoaded = new RelayCommand(
() => Loaded()
);
}
return _PageLoaded;
}
}
如果这个问题仍然存在,我更喜欢这个解决方案:http://www.geoffhudik.com/tech/2010/10/10/another-wp7-navigation-approach-with-mvvm.html
如果要使用它,可以从发送方ViewModel:发送接收方ViewModel的参数
SendNavigationMessage(Settings.NAVIGATION_PRODUCTS_SUBCATEGORIES,
new Dictionary<string, object> { { "SelectedIndex", Int32.Parse(item.id) } });
接收器应在xaml:中定义
NavigatedToCommand="{Binding RefreshCommand}"
然后在接收器视图模型:
public ICommand RefreshCommand // Should be set as NavigatedToCommand="{Binding RefreshCommand}" in xaml
{
get { return new RelayCommand(Refresh); }
}
public void Refresh()
{
_dataService.GetList(SelectedIndex, DownloadedCallback); // So, this would be called automatically after navigating is complete. SelectedIndex is updated at this moment.
}
感谢您提供的答案。在一段时间内,两者都很有帮助,直到我决定创建一个由几个人创建的导航服务的自定义实现。然后,我对Cimbalino工具包做出了贡献,提出了这一点,它已经在不久前推出了。
我个人认为,这能最好地解决我的问题。看看那里的导航服务。Navigated事件基本上解决了我的问题。
https://github.com/Cimbalino/Cimbalino-Toolkit
基本上可以归结为(在视图模型中):
_navigationService.Navigated += OnNavigated;