单击btn更改资源文件引用
本文关键字:源文件 引用 资源 btn 单击 | 更新日期: 2023-09-27 17:58:33
我正在为用户实现一种切换所显示语言(en||es)的方法。我有以下内容:
<asp:LinkButton ID="Lnk_cultChange" runat="server" Text="<%$Resources:mySource, cultbtn%>" OnClick="cultChange_Click" />
代码背后:
protected void cultChange_Click(object sender, EventArgs e)
{
if (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en")
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
base.InitializeCulture();
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
base.InitializeCulture();
}
}
有一个回发,但似乎什么也没发生。英文资源文件仍在显示,并且没有进行翻译。我的实施正确吗?
切换页面上的区域性PreInit事件,如果只想在单击特定按钮时切换区域性,请使用以下代码。
protected override void OnPreInit(EventArgs e)
{
if (Page.IsPostBack)
{
if (Request.Form["__EVENTTARGET"] == "Lnk_cultChange")
{
if (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en")
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
base.InitializeCulture();
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
base.InitializeCulture();
}
}
}
base.OnPreInit(e);
}
请求。表单["__EVENTTARGET"]将是您的LinkButton的客户端ID,请告诉我这是否不起作用
将更改lang按钮放在站点主控器中。添加点击事件处理程序,如以下
protected void btnEng_Click(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en");
Session.Add("Lang", "en");
Response.Redirect(Request.Url.PathAndQuery);
}
在页面的代码后面添加以下方法:
protected override void InitializeCulture()
{
if (Session["Lang"] != null)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Session["Lang"].ToString().Split('-')[0]);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Session["Lang"].ToString().Split('-')[0]);
}
else
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
}
base.InitializeCulture();
}
希望对有所帮助
就像@Umriyaev建议的那样,您必须重写InitializeCulture()
,并在另一次重定向后使用它来拉取区域性。请参阅此处https://stackoverflow.com/a/10672476/2596756