这个问题有点晚了,但它是相关的,希望对某人有所帮助。我必须使用 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接口,依赖MainPage.xaml.cs的NavigationFrame属性获取导航框架的引用:
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;
}
}