在代码后台中编程更改资源文件语言(resx)

8

我有一个用C#编写的.Net应用程序,文件结构大致如下:

App_LocalResources
 - MyPage.aspx.resx
 - MyPage.aspx.fr.resx
MyPage.aspx
MyPage.aspx.cs

我想在代码后台文件(MyPage.aspx.cs)中编程更改语言,以告诉应用程序使用哪个resx文件。我已经尝试在OnPreRender、Page_Init和Page_Load事件中使用以下两种方法:

Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA");

但是它没有起作用。页面仍然显示英语。MyPage.aspx文件包含以下内容:

<h3><asp:Literal runat="server" Text="<%$ Resources:pageTitle %>" /></h3>

请注意,我不能关心浏览器语言。它必须覆盖此内容。我一直在网上寻找解决方案,但没有找到。所有示例都显示已尝试过的切换语言的方式(如上所述),但这不会影响使用的资源文件。有什么想法吗?

1个回答

13

您必须重写InitializeCulture方法并将代码放在其中。例如:

protected override void InitializeCulture()
{
   base.InitializeCulture();
   System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-CA");
   System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA");
}
希望这有所帮助。

1
MartinB,你让我印象深刻,谢谢。可能是我用的搜索词不对,或者网上关于这个问题的信息很少。这个方法完美地解决了我的问题。我很高兴这个答案会被放在 Stack Overflow 上,供未来寻找答案的人参考。谢谢! - Sherri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接