配置默认首页
当应用程序启动时,默认显示首页
一.实现思路,通过自定义接口来配置应用程序加载完成时,设置默认显示页
步骤1.创建自定义 IConfigureService 接口
cs
namespace MyToDo.Common
{
/// <summary>
/// 配置默认显示页接口
/// </summary>
public interface IConfigureService
{
void Configure();
}
}
步骤2.MainViewModel 去继承并实现该接口。同时把初始化菜单操作,以及配置默认启动页操作在该方法中去处理。
cs
namespace MyToDo.ViewModels
{
public class MainViewModel: BindableBase, IConfigureService
{
public MainViewModel(IRegionManager regionManager)
{
MenuBars=new ObservableCollection<MenuBar>();
NavigateCommand = new DelegateCommand<MenuBar>(Navigate);
this.regionManager = regionManager;
GoBackCommand = new DelegateCommand(() =>
{
if(journal!=null && journal.CanGoBack) journal.GoBack();
});
GoForwardCommand = new DelegateCommand(() =>
{
if (journal != null && journal.CanGoForward) journal.GoForward();
});
}
/// <summary>
/// 导航方法
/// </summary>
/// <param name="bar">菜单</param>
private void Navigate(MenuBar bar)
{
//命名空间为空,不进行导航
if (bar == null || string.IsNullOrEmpty(bar.NameSpace)) return;
regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(bar.NameSpace, back =>
{
journal=back.Context.NavigationService.Journal;
});
}
/// <summary>
/// 导航命令
/// </summary>
public DelegateCommand<MenuBar> NavigateCommand { get; private set; }
/// <summary>
/// 下一步
/// </summary>
public DelegateCommand GoBackCommand { get; private set; }
/// <summary>
/// 上一步
/// </summary>
public DelegateCommand GoForwardCommand { get; private set; }
private ObservableCollection<MenuBar> menuBars;
private readonly IRegionManager regionManager;
/// <summary>
/// 导航日志
/// </summary>
private IRegionNavigationJournal journal;
public ObservableCollection<MenuBar> MenuBars
{
get { return menuBars; }
set { menuBars = value; RaisePropertyChanged(); }
}
void CreateMenuBar()
{
MenuBars.Add(new MenuBar() { Icon="Home",Title="首页",NameSpace="IndexView"});
MenuBars.Add(new MenuBar() { Icon = "NotebookCheckOutline", Title = "待办事项", NameSpace = "ToDoView" });
MenuBars.Add(new MenuBar() { Icon = "NotebookPlusOutline", Title = "忘备录", NameSpace = "MemoView" });
MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingsView" });
}
public void Configure()
{
CreateMenuBar();
regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("IndexView");
}
}
}
- RequestNavigate 里面直接填写字符串就能该到该视图,是因为所有的视图都已在 App中进行依赖注入了。所以Prism能直接通过对应的字符串找到对应的视图。
步骤3.在 App中,当应用程序主窗口加载完成的时候,通过重写OnInitialized 方法,在该方法中通过拿到主窗口实例,去调用到自定义的方法来实现加载设置的默认首页。
cs
protected override void OnInitialized()
{
var service= App.Current.MainWindow.DataContext as IConfigureService;
if (service != null) service.Configure();
base.OnInitialized();
}