(三)菜单导航
菜单导航
1. 准备工作
- 新建文件夹与类,创建我们需要的页面
- 视图层是新建的用户控件与最初主页不同(主页是窗体)
![image]()
- 可以给每个页面一个简单的内容用于测试,例如
<TextBlock FontSize="80" Text="index" />
2. 将页面注册为导航
app.xaml.cs
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
//注册为导航
containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
containerRegistry.RegisterForNavigation<ToDoView, ToDoViewModel>();
containerRegistry.RegisterForNavigation<MemoView, MemoViewModel>();
containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();
}
3. 添加命令用于驱动导航
DelegateCommand是ICommand 的实现,其中,执行和 CanExecute 回调由委托处理。
4. 添加区域来进行导航实现
- 引入接口
![image]()
- 视图添加区域
![image]()
- 用单独的类来管理区域注册
![image]()
- 添加静态类
public static class PrismManager
{
public static readonly string MainViewRegionName = "MainViewRegion";
}
- 添加命名空间使用这个类
![image]()
- 使用静态引用,后台就可以直接使用
<ContentControl prism:RegionManager.RegionName="{x:Static ext:PrismManager.MainViewRegionName}"/>
- 后台使用区域
RequestNavigate: 进行页面切换,将指定的Region中显示的视图切换为指定的视图。
5. 前进回退实现
- 实例化日志
![image]()
- 定义2个命令用于实现按钮
public DelegateCommand GoBackCommand { get; private set; }
public DelegateCommand GoForwardCommand { get; private set; }
- 与视图绑定
![image]()
- 在构造函数实现
GoBackCommand = new DelegateCommand(() =>
{
if (journal != null && journal.CanGoBack) { journal.GoBack(); }
});
GoForwardCommand = new DelegateCommand(() =>
{
if (journal != null && journal.CanGoForward) { journal.GoForward(); }
});
6. 视图层的行为实现
- 在包管理器中下载
![image]()
- 命名空间引入
![image]()
- listbox添加名字x:Name="menuBar"
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged"><!--触发事件:被选择-->
<i:InvokeCommandAction
Command="{Binding NavigateCommand}"
CommandParameter="{Binding ElementName=menuBar,Path=SelectedItem}"/>
<!--绑定的命令NavigateCommand 传递参数是菜单列表,绑定的是被选择的那一项-->
</i:EventTrigger>
</i:Interaction.Triggers>
7. 切换页面时菜单栏收缩
- 给菜单栏添加名字,方法中会用到
![image]()
- mainview.xaml.cs
//切换页面菜单栏的收缩
menuBar.SelectionChanged += (s, e) =>
{
drawerHost.IsLeftDrawerOpen = false;
};














浙公网安备 33010602011771号