Xamarin/C#如何配置App.Current.Properties字典避免键不存在异常
解决方案
异常原因
你触发KeyNotFoundException的核心原因是:仅在首次启动/点击修改按钮的场景下才会给Application.Current.Properties["LeaveDays"]赋值,其余场景(比如非首次启动且未触发修改逻辑)直接通过索引器读取该不存在的键就会抛出异常。此外你当前代码修改完属性字典后没有触发持久化保存,重启应用后数据还是会丢失。
具体修改步骤
- 所有读取
LeaveDays的逻辑先做键存在性判断,不要直接用索引器读取,推荐用TryGetValue方法安全取值 - 给属性字典赋值完成后,立即调用
SavePropertiesAsync()将修改持久化到本地存储 - 补充弹窗取消逻辑的判断,避免将
null值存入属性字典
修改后的代码
async void SetLeaveDaysPopup() { VersionTracking.Track(); var firstLaunch = VersionTracking.IsFirstLaunchEver; if (firstLaunch == true || ChangeLeaveDaysButton.IsEnabled == true) { var inputResult = await DisplayPromptAsync("Set Leave Days", "Please set the amount of total leave days you have"); // 处理用户点击取消的情况,不保存空值 if (!string.IsNullOrEmpty(inputResult)) { Application.Current.Properties["LeaveDays"] = inputResult; // 持久化保存修改 await Application.Current.SavePropertiesAsync(); EntitlementDaysText.Text = inputResult; calculateLeaveHours(inputResult); } } }
其他场景读取该值的示例
不要直接用Application.Current.Properties["LeaveDays"]读取,用如下安全逻辑即可实现无初始值的适配要求:
if (Application.Current.Properties.TryGetValue("LeaveDays", out var leaveDaysObj) && leaveDaysObj is string leaveDays && !string.IsNullOrEmpty(leaveDays)) { // 拿到有效值的业务逻辑 EntitlementDaysText.Text = leaveDays; calculateLeaveHours(leaveDays); } else { // 无有效值时触发弹窗要求用户输入 await SetLeaveDaysPopup(); }
内容的提问来源于stack exchange,提问作者aTubOfAdam
相关产品推荐
相关产品推荐

