在上兩篇(1,2)中提到了如何在應用程式項目中使用資源檔的問題,還沒有測試在調用其他ClassLibrary中資源檔的情況,今早起來還按照以往ASP.NET項目中的作法做個測試
使用資源檔:
public class Class1 { public string GetTT() { return Resources.Test.TT; } }
期望能像往常一樣,隨著瀏覽器中的語言選項的變換能出現自動轉場效果,結果不出意料的失望了,只能顯示沒有帶Culture資訊的資源項值。
(3月22日重要更新內容:在web.config的system.web配置節點下加入<globalization culture="auto" uiCulture="auto"/>就可以不使用下列的方法了,唉,學藝不精啊!!!)
通過檢查資源檔的Designer.cs檔案,發現其內部有一個屬性定義:
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } }
於是猜想,如果能設定這個屬性值,想必可以讓ResourceManager自動選取相應的資源檔吧,但是添加在哪裡呢,發現在HttpApplication中有這樣一個事件:
public event EventHandler PreRequestHandlerExecute;
於是在Global裡面添加了這個事件的事件處理器,並在其方法內部添加如下代碼:
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e) { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(Request.UserLanguages[0]); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; }
F5運行,果然達到了預期的效果:隨著瀏覽器語言選項的切換,頁面上的語言也能自動切換了。
英文:
中文: