WinUI中如何获取ContentFrame.Navigate传递的DbContext参数?
解决方案
方法一:直接获取Navigate传递的DbContext参数
在PlayersPage中重写OnNavigatedTo方法,通过导航事件参数拿到传递的DbContext:
using Microsoft.UI.Xaml.Navigation; // 替换为你的DbContext实际类型 using YourNamespace.Models; public sealed partial class PlayersPage : Page { private YourDbContextType _context; public PlayersPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // 校验参数类型并赋值 if (e.Parameter is YourDbContextType dbContext) { _context = dbContext; // 此处可直接使用_context进行数据操作 } } }
通过这个方式,就能直接获取ContentFrame.Navigate(typeof(PlayersPage), _context);传递的DbContext实例。
方法二:修复依赖注入的报错问题
出现的NullReferenceException是因为UWP默认通过XAML类型加载器创建页面,仅支持调用无参构造函数。要实现DbContext注入,需改用依赖注入容器创建页面实例,步骤如下:
- 注册DbContext到服务容器
在App.xaml.cs中初始化服务容器并完成DbContext的注册:
using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; // 替换为你的DbContext实际类型 using YourNamespace.Models; public partial class App : Application { // 全局可访问的服务容器实例 public static IServiceProvider ServiceProvider { get; private set; } protected override void OnLaunched(LaunchActivatedEventArgs e) { var services = new ServiceCollection(); // 注册DbContext,根据你的数据库类型配置对应选项 services.AddDbContext<YourDbContextType>(options => { options.UseSqlite("Data Source=GameTools.db"); // 若使用SQL Server等其他数据库,替换为对应的UseSqlServer等方法 }); // 将PlayersPage注册到服务容器,由DI管理实例 services.AddTransient<PlayersPage>(); ServiceProvider = services.BuildServiceProvider(); // 初始化应用主窗口 if (Window.Current.Content == null) { Window.Current.Content = new MainPage(); } Window.Current.Activate(); } }
- 修改PlayersPage的构造函数
添加接收DbContext的构造函数,让DI容器可以注入实例:
public sealed partial class PlayersPage : Page { private readonly YourDbContextType _context; // 依赖注入构造函数 public PlayersPage(YourDbContextType context) { this.InitializeComponent(); _context = context; // 页面初始化时即可使用_context } }
- 通过DI获取页面实例并导航
在NavView_ItemInvoked方法中,从服务容器获取PlayersPage实例后再导航:
private void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args) { // 从全局服务容器获取PlayersPage实例 var playersPage = App.ServiceProvider.GetRequiredService<PlayersPage>(); // 导航到该实例,无需额外传递参数(构造函数已完成注入) ContentFrame.Navigate(playersPage.GetType()); }
这样就能避免XAML加载器创建实例时的报错,同时通过依赖注入拿到DbContext。
内容的提问来源于stack exchange,提问作者Silny ToJa
相关产品推荐
相关产品推荐

