說明:一般ASP.NET網頁都是override InitializeCulture method來轉換語系,但因MasterPage是繼承MasterPage class(UserControl),無提供InitializeCulture method。
作法:
1. 自訂一BasePage class(放於App_Code)並繼承Page class,在BasePage中override InitializeCulture method,再使各page從繼承Page改為namespace.BasePage,例:
BasePage.cs
namespace Web
{
public class BasePage : Page
{
protected override void InitializeCulture()
{
string culture = Session["culture"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
base.InitializeCulture();
}
}
}
再搭配如DropDownList等控制項供選擇,例:
xxx.aspx
<asp:DropDownList ID="ddlLanguage" runat="server" AutoPostBack="True" onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
<asp:ListItem Value="zh-TW" Text="<%$ Resources:PageResource, LanguageZh %>"></asp:ListItem>
<asp:ListItem Value="en-US" Text="<%$ Resources:PageResource, LanguageEn %>"></asp:ListItem></asp:DropDownList>
xxx.aspx.cs
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddlLanguage.SelectedIndex > 0)
{
Session["culture"] = this.ddlLanguage.SelectedValue;
//reload request page
Server.Transfer(Request.Path);
}
}
參考資料:
http://stackoverflow.com/questions/11805897/masterpage-initializeculture-no-suitable-method-found-to-override-error
2. 透過global.asax。
沒有留言:
張貼留言