.NET 9.0 MAUI本地化资源引用编译错误求助
.NET 9 MAUI多语言资源调用问题解决方法
问题概述
- 升级至.NET 9后,Resources文件夹文件自动包含,但调用
local:AppResources.WELCOME时代码标红、编译失败 - 项目文件设置
EnableDefaultItems=true无效,未生成AppResources.Designer.cs - Mac上的Visual Studio Code无「embed...」上下文菜单
- XAML错误提示:
Cannot resolve type "http://schemas.microsoft.com/dotnet/2021/maui:local.AppResources"
解决步骤
1. 手动配置资源文件生成强类型类
.NET 9 MAUI默认不会自动生成AppResources.Designer.cs,需手动编辑项目文件(.csproj)添加配置:
<ItemGroup> <!-- 默认语言资源 --> <EmbeddedResource Update="Resources\AppResources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>AppResources.Designer.cs</LastGenOutput> </EmbeddedResource> <!-- 德语资源 --> <EmbeddedResource Update="Resources\AppResources.de.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>AppResources.de.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup>
保存后重新生成项目,AppResources.Designer.cs会自动生成在Resources目录下。
2. 修正XAML命名空间与调用语法
- 确认
local命名空间指向项目根命名空间(如MotivationByAudio),与AppResources.Designer.cs中的命名空间一致:xmlns:local="using:MotivationByAudio" - 确保调用语法正确,使用生成的强类型类名
AppResources:<Label Text="{x:Static local:AppResources.WELCOME}" ... />
3. 验证资源文件构建操作
确保资源文件的Build Action为Embedded Resource,通过项目文件配置已自动设置此属性,无需额外操作。
4. 启用多语言支持(可选)
在MauiProgram.cs中添加本地化服务:
builder.Services.AddLocalization();
如需切换文化,可在App.xaml.cs中设置:
using System.Globalization; namespace MotivationByAudio; public partial class App : Application { public App() { InitializeComponent(); // 示例:切换为德语 CultureInfo.CurrentCulture = new CultureInfo("de-DE"); CultureInfo.CurrentUICulture = new CultureInfo("de-DE"); MainPage = new MainPage(); } }
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

