这个问题有点晚了,但它是相关的,希望对某人有益。我不得不用MvvmLight创建一个SL4应用程序,并且想要使用一个可以模拟的导航服务包装,并且可以注入到ViewModel中。我在这里找到了一个很好的起点:来自Mix11的Laurent Bugnion的SL4示例代码示例包括一个导航服务演示:Deep Dive MVVM Mix11
以下是实现可用于Silverlight 4的模拟导航服务的基本部分。关键问题是获取对自定义NavigationService类中使用的主导航框架的引用。
1)在MainPage.xaml中,导航帧被给予一个唯一的名称,在这个例子这将是ContentFrame:
<navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}"
Source="/Home" Navigated="ContentFrame_Navigated"
NavigationFailed="ContentFrame_NavigationFailed">
<!-- UriMappers here -->
</navigation:Frame>
2)在MainPage.xaml.cs中,导航框架露出作为属性:
public Frame NavigationFrame
{
get { return ContentFrame; }
}
3)所述的导航服务类实现INavigationService接口和依赖于NavigationFrame适当MainPage.xaml.cs获取对导航框架的引用:
public interface INavigationService
{
event NavigatingCancelEventHandler Navigating;
void NavigateTo(Uri uri);
void GoBack();
}
public class NavigationService : INavigationService
{
private Frame _mainFrame;
public event NavigatingCancelEventHandler Navigating;
public void NavigateTo(Uri pageUri)
{
if (EnsureMainFrame())
_mainFrame.Navigate(pageUri);
}
public void GoBack()
{
if (EnsureMainFrame() && _mainFrame.CanGoBack)
_mainFrame.GoBack();
}
private bool EnsureMainFrame()
{
if (_mainFrame != null)
return true;
var mainPage = (Application.Current.RootVisual as MainPage);
if (mainPage != null)
{
// **** Here is the reference to the navigation frame exposed earlier in steps 1,2
_mainFrame = mainPage.NavigationFrame;
if (_mainFrame != null)
{
// Could be null if the app runs inside a design tool
_mainFrame.Navigating += (s, e) =>
{
if (Navigating != null)
{
Navigating(s, e);
}
};
return true;
}
}
return false;
}
}
其实它是你的选择你如何实现模式以及如何解决这样的问题。也许最好的做法是使用像MVVM Ligh Messenger之类的消息传递,因此从ViewModel发送一条消息,使得View应该导航,并且有一个资源类或者可以在你的Views之间导航的东西。 :) – BigL 2012-01-15 10:31:55