[英]Page won't change language
我的页面不会更改语言,有人可以看一下我的代码并告诉我我做错了什么,它总是使用默认语言
public partial class ChangeLanguage : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
SortedDictionary<string, string> objDic = new SortedDictionary<string, string>();
foreach (CultureInfo ObjectCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo objRegionInfo = new RegionInfo(ObjectCultureInfo.Name);
if (!objDic.ContainsKey(objRegionInfo.EnglishName))
{
objDic.Add(objRegionInfo.EnglishName, ObjectCultureInfo.Name);
}
}
foreach (KeyValuePair<string, string> val in objDic)
{
ddlCountries.Items.Add(new ListItem(val.Key, val.Value));
}
ddlCountries.SelectedValue = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
}
protected void btnChangeLanguage_Click(object sender, EventArgs e)
{
ProfileCommon profile = HttpContext.Current.Profile as ProfileCommon;
profile.Preferences.Culture = ddlCountries.SelectedValue;
}
}
protected override void InitializeCulture()
{
string culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
this.Culture = culture;
this.UICulture = culture;
}
Profile:
<properties>
<add name="FirstName" type="String"/>
<add name="LastName" type="String"/>
<add name="Gender" type="String"/>
<add name="BirthDate" type="DateTime"/>
<add name="Occupation" type="String"/>
<add name="WebSite" type="String"/>
<group name="Preferences">
<add name="Culture" type="String" defaultValue="en-NZ" allowAnonymous="true"/>
</group>
</properties>
这里有几个问题,但主要的问题是您在Page_Load中会这样做:
ddlCountries.SelectedValue = (HttpContext.Current.Profile as ProfileCommon
然后在点击事件的事件处理程序中执行以下操作:
profile.Preferences.Culture = ddlCountries.SelectedValue;
对于您来说不幸的是,Page_Load事件在单击事件之前触发,并且由于Page_Load事件将dropdownlist的selectedvalue设置为Profile对象中已存储的值,然后保存了dropdownlist的selectedvalue(不再是您选择的值)。在点击按钮之前选择),实际上,您只是忽略所选值,而是继续使用默认值(或以前的值)。
将在下拉列表中选择值的代码移动到Page_PreRender(将其从Page_Load中删除),您会很好的(示例):
protected void Page_PreRender(object sender, EventArgs e)
{
string culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
if (ddlCountries.Items.FindByValue(culture) != null)
{
ddlCountries.SelectedValue = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.