WinUI3 TemplateStudio使用ILocalSettingsService读本地设置遇空引用异常
解决WinUI3 TemplateStudio中ILocalSettingsService空引用异常
核心原因
空引用异常源于_settingsService未被正确初始化——TemplateStudio依赖注入框架要求通过构造函数注入ILocalSettingsService实例,若页面未在构造函数中接收并赋值该实例,会导致_settingsService为null。
修复步骤
1. 通过构造函数注入服务
修改页面类的构造函数,添加ILocalSettingsService参数并赋值给私有字段:
using Microsoft.TemplateStudio.UI.Services; private readonly ILocalSettingsService _settingsService; // 替换YourPage为你的页面类名 public YourPage(ILocalSettingsService settingsService) { InitializeComponent(); _settingsService = settingsService; }
2. 修正异步方法调用逻辑
ReadSettingAsync是异步方法,直接使用.Result易引发UI线程死锁,改用async/await调用:
private async void Page_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { // 注意:原代码键名拼写错误——notifiacations → notifications var notifications = await _settingsService.ReadSettingAsync<string>("notifications"); var notificationsSound = await _settingsService.ReadSettingAsync<string>("notifications.sound"); NotificationToggle.IsOn = notifications == "on"; NotificationSoundToggle.IsOn = notificationsSound == "on"; }
3. 修正键名拼写错误
原代码中第一个设置键名写成notifiacations(缺失字母t),会导致无法读取正确配置,需修正为notifications。
内容的提问来源于stack exchange,提问作者Luis
相关产品推荐
相关产品推荐

