2014-09-10 33 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