2014-09-10 16 views
1

设置文化时,我设置的页面文化在运行时代码隐藏这样的资源文件不工作:定位在运行时

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); 
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR"); 
Page.Culture = "fr-FR"; 

资源文件是在GlobalResource文件夹,我已经有2个文件:SomeFile.resxSomeFile.fr.resx

在标记页面,我有文字,看起来像这样:

<asp:Literal runat="server" ID="test" Text="<%$ Resources:SomeFile, SomeKey%>" /> 

如果SE中的代码如果文化被注释掉,那么文字将采用SomeFile.resx中的值,但是如果我运行设置文化的代码,那么我也会得到SomeFile.resx文件中的值,而不是SomeFile.fr.resx文件中的值。我也尝试将文化信息设置为“fr”,以查看这是否有所作为,但没有。

我需要改变什么?

谢谢。

+0

设置文化后,从资源中获取字符串是否正确工作(类似于'var s = SomeResources.SomeKey;',假设您已经为resx启用了auo-generation)? – 2014-09-10 16:31:26

回答

0

好,对于那些谁到这里来,我已经想通了。

1)将资源文件放在App_GlobalResources文件夹中。例如,你可能有SomeFile.resxSomeFile.fr.resx

2)在后面的代码,这样设置文化:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); 
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR"); 
Page.Culture = "fr-FR"; 

3)然后,要访问值,你这样写:

string SomeValue = GetGlobalResourceObject("SomeFile", "SomeKey").ToString(); 

我认为是最简单的方法来做到这一点。

+0

不要抱怨,但这与我在两小时前提供的答案几乎相同。为什么这个答案标记正确? – Kjata30 2016-05-16 20:32:20

+0

frenchie,帖子有点老了,但是你是否在控制器中设置了文化,例如,如果这是正确的方式,文化将被更改为所有请求的视图之后......然后可能将文化存储在一些cookie中或会话变量或其他 – 2017-05-05 06:08:52

2

用于查找本地化资源的Microsoft article为如何执行此操作提供了一个很好的示例。从你写的是什么,它看起来像你是不是创建一个新的ResourceManager对象使用文化:

private ResourceManager rm { get; set; } 

protected void Page_Load() 
{ 
    var newCulture = new CultureInfo("fr-FR"); 
    Thread.CurrentThread.CurrentCulture = newCulture; 
    Thread.CurrentThread.CurrentUICulture = newCulture; 
    Page.Culture = "fr-FR"; 
    this.rm = new ResourceManager("SomeFile", typeof(Program).Assembly); 

    this.test.Text = rm.GetString("SomeKey"); 
} 
+0

此行导致问题:this.rm = new ResourceManager(“SomeFile”,typeof(Program).Assembly);这是用于桌面应用程序,我有一个asp.net应用程序。 – frenchie 2014-09-10 20:05:19

+0

Upvoted因为你的解决方案让我走上正轨。 – frenchie 2014-09-10 20:20:59

+0

我用'Assembly.GetExecutingAssembly()'代替'typeof(程序).Assembly' – Zanon 2015-12-08 12:50:55