You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Avalonia UI中使用MediatR实现视图间导航?

在Avalonia UI中使用MediatR实现视图导航

1. 定义导航请求类

先创建MediatR请求类,用于传递目标视图的类型信息:

public class NavigateRequest : IRequest
{
    public Type TargetViewType { get; }

    public NavigateRequest(Type targetViewType)
    {
        TargetViewType = targetViewType;
    }
}

2. 实现导航请求处理器

创建处理器处理导航逻辑,这里假设主窗口中存在名为MainContent的ContentControl作为视图容器:

public class NavigateRequestHandler : IRequestHandler<NavigateRequest>
{
    private readonly IServiceProvider _serviceProvider;
    private readonly MainWindow _mainWindow;

    public NavigateRequestHandler(IServiceProvider serviceProvider, MainWindow mainWindow)
    {
        _serviceProvider = serviceProvider;
        _mainWindow = mainWindow;
    }

    public Task Handle(NavigateRequest request, CancellationToken cancellationToken)
    {
        // 从DI容器解析目标视图实例
        var targetView = _serviceProvider.GetService(request.TargetViewType) as Control;
        if (targetView != null)
        {
            _mainWindow.MainContent.Content = targetView;
        }
        return Task.CompletedTask;
    }
}

3. 注册服务到DI容器

在Avalonia的服务配置中(比如Program.cs),注册MediatR、视图及主窗口:

public static AppBuilder BuildAvaloniaApp()
{
    return AppBuilder.Configure<App>()
        .UsePlatformDetect()
        .LogToTrace()
        .ConfigureServices(services =>
        {
            // 注册MediatR并扫描当前程序集的处理器
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(NavigateRequest).Assembly));
            
            // 注册两个目标视图,生命周期按需选择瞬时/单例
            services.AddTransient<AdminPageView>();
            services.AddTransient<UserPageView>();
            
            // 注册主窗口供处理器注入
            services.AddSingleton<MainWindow>();
        });
}

4. 发起导航请求

在需要触发导航的视图模型中,注入IMediator并发送请求:

public class NavigationViewModel
{
    private readonly IMediator _mediator;

    public NavigationViewModel(IMediator mediator)
    {
        _mediator = mediator;
        NavigateToAdminCmd = new RelayCommand(async () => 
            await _mediator.Send(new NavigateRequest(typeof(AdminPageView))));
        NavigateToUserCmd = new RelayCommand(async () => 
            await _mediator.Send(new NavigateRequest(typeof(UserPageView))));
    }

    public ICommand NavigateToAdminCmd { get; }
    public ICommand NavigateToUserCmd { get; }
}

注:如果未使用第三方命令库,可以用Avalonia自带的ReactiveCommand或自行实现简单命令类。

5. 主窗口布局配置

确保MainWindow.axaml中包含视图容器:

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="YourAppNamespace.MainWindow"
        Title="NavigationDemo">
    <Grid>
        <!-- 用于承载切换视图的容器 -->
        <ContentControl x:Name="MainContent" />
    </Grid>
</Window>

额外说明

  • 如需传递导航参数,可扩展NavigateRequest类添加Parameters属性,在处理器中传递给目标视图或视图模型。
  • 若使用Avalonia MVVM Toolkit,可结合框架自带的DI机制简化服务注入流程。

内容的提问来源于stack exchange,提问作者gary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 09:19:58