WPF区域导航+导航参数使用+路由守卫+导航日志

背景:使用ContentControl控件实现区域导航是有Mvvm框架的WPF都能使用的,不限于Prism

主要是将ContenControl控件的Content内容在ViewModel中切换成不同的用户控件

下面是MainViewModel:

private object body;

public object Body
{
    get { return body; }
    set { body = value; RaisePropertyChanged(); }
}


public DelegateCommand<string> OpenCommand { get; set; }

public MainWindowViewModel()
{
    OpenCommand = new DelegateCommand<string>(obj =>
    {
        Body = obj switch
        {
            "ViewA" => new ViewA(),
            "ViewB" => new ViewB(),
            "ViewC" => new ViewC(),
            _ => Body
        };
    });
}


上面是有Mvvm框架就行了,每次打开新的模块就创建一个用户控件对象

下面是使用Prism框架的导航实现会方便一些

1.首先在App.xaml.cs中注入用户控件的依赖

2.ContentControl中的Content修改为:

<ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" />

3.MainWindowViewModel变成:

public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager regionManager;

    public DelegateCommand<string> OpenCommand { get; set; }

    public MainWindowViewModel(IRegionManager regionManager)
    {
        OpenCommand = new DelegateCommand<string>(obj => { regionManager.Regions["ContentRegion"].RequestNavigate(obj); });
        this.regionManager = regionManager;
    }
}

-- 也就是由创建用户控件,变成调用依赖注入的用户控件

导航参数

在调用导航前设置导航参数,请求导航的时候将导航参数传递过去

NavigationParameters keys = new NavigationParameters();
keys.Add("Title", "Hello");

regionManager.Regions["ContentRegion"].RequestNavigate(viewName, keys);

然后导航用户控件的ViewModel需要接口INavigationAware,接口重写方法中都是带有参数NavigationContext的,然后通过它获取导航参数就行

public void OnNavigatedTo(NavigationContext navigationContext)
{
    if (navigationContext.Parameters.ContainsKey("Title"))
        Tile = navigationContext.Parameters.GetValue<string>("Title");
}

路由守卫

需要实现路由守卫需要将原本的INavigationAware接口换成IConfirmNavigationRequest,重写的方法如果continuationCallback的值是true就给导航过去,如果没有就不给导航

public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{
    bool result = true;

    if (MessageBox.Show("请求导航?", "温馨提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
    {
        result = false;
    }

    continuationCallback(result);
}

导航日志

private IRegionNavigationJournal journal;
// 打开区域的方法
private void OpenView(string viewName)
{
    NavigationParameters keys = new NavigationParameters();
    keys.Add("Title", "Hello");

    // 调用完区域就记录在日志中
    regionManager.Regions["ContentRegion"].RequestNavigate(viewName, callBack =>
    {
        if (callBack.Cancelled)
        {
            return;
        }
        journal = callBack.Context.NavigationService.Journal;
    }, keys);
}

//返回上一页方法(让按钮绑定就行)
private void back()
{
    if (journal.CanGoBack)
        journal.GoBack();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值