WinUI3 TemplateStudio应用访问Resources.resw字符串报错求助
WinUI桌面应用访问本地化字符串报错解决方案
问题描述
- 使用WinUI桌面版TemplateStudio模板,
Strings/en-us/Resources.resw存储本地化字符串,ShellPage通过XAML的Uid属性映射导航页标题。 - 在页面加载时尝试通过代码提取字符串,使用
ResourceLoader.GetForCurrentView()后抛出运行时错误:System.Runtime.InteropServices.COMException: Resource Contexts may not be created on threads that do not have a CoreWindow. (0x80073B27)
解决方案
将ResourceLoader.GetForCurrentView()替换为**ResourceLoader.GetForViewIndependentUse()**,该方法不依赖CoreWindow,适配WinUI桌面应用的线程上下文场景。
修改后的代码示例:
public sealed partial class TransactionDetailPage : Page { public TransactionDetailPage() { this.InitializeComponent(); Loaded += (s, e) => { var rl = Windows.ApplicationModel.Resources.ResourceLoader.GetForViewIndependentUse(); App.CurrentPageTitle = rl.GetString("TransactionDetailPage.Title"); }; } }
原因说明
GetForCurrentView()要求当前线程关联CoreWindow才能创建资源上下文,但WinUI桌面应用(尤其是基于Win32打包的版本)的UI线程可能不具备该关联条件,导致报错。GetForViewIndependentUse()是独立于视图的资源加载方法,专门针对桌面环境的本地化需求设计,不会受CoreWindow限制。
内容的提问来源于stack exchange,提问作者apps2go
相关产品推荐
相关产品推荐

