我的页面不会改变语言,有人可以查看我的代码并告诉我我做错了它总是使用默认语言
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>
答案 0 :(得分:2)
这里有几个问题,但主要的一个是你在Page_Load做:
ddlCountries.SelectedValue = (HttpContext.Current.Profile as ProfileCommon
然后在click事件的eventhandler中执行:
profile.Preferences.Culture = ddlCountries.SelectedValue;
不幸的是,Page_Load事件在点击事件之前触发,并且因为Page_Load事件将下拉列表的选定值设置为已存储在Profile对象中的值 ,然后保存下拉列表的选定值(不再是您在单击按钮之前选择的值),基本上只是忽略所选值并继续使用默认值(或以前的值)。
将选择下拉列表中的值的代码移动到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;
}
}