我已经构建了以下自定义控件,并且在单击项目符号列表项时设置了所选值。
我的问题是我需要在回发后设置css类(SetSelected()),但它总是在视图状态中选取上一个条目而不是获取新值。
我认为我不应该使用PageLoad来设置CSS类,但我不确定在哪里做到最好。
有人可以帮忙吗?
[DefaultProperty("SelectedValue"),
ToolboxData("<{0}:GlossaryList runat=\"server\" />")]
public class GlossaryList : WebControl
{
const string MANAGEDMETADATASERVICE = "Managed Metadata Service";
const string TOYOTA = "Toyota";
BulletedList _bulletList = new BulletedList();
public String SelectedText
{
get
{
object selectedText = ViewState["SelectedText"];
return (selectedText == null) ? String.Empty : (string)selectedText;
}
set
{
ViewState["SelectedText"] = value;
}
}
public String SelectedValue
{
get
{
object selectedValue = ViewState["SelectedValue"];
return (selectedValue == null) ? String.Empty : (string)selectedValue;
}
set
{
ViewState["SelectedValue"] = value;
}
}
protected override void OnInit(EventArgs e)
{
CreateBulletedList();
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
if (this.Page.IsPostBack)
{
SetSelected();
}
base.OnLoad(e);
}
private void SetSelected()
{
//if(this.Controls != null && this.Controls.Count > 0)
//{
// foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
// {
// if (listItem.Value == SelectedValue)
// {
// listItem.Attributes.Add("class", "active");
// }
// }
//}
}
protected void CreateBulletedList()
{
_bulletList.Click += new BulletedListEventHandler(BulletListItem_Click);
_bulletList.DisplayMode = BulletedListDisplayMode.LinkButton;
_bulletList.CssClass = "letter-selector";
for (char c = 'A'; c <= 'Z'; c++)
{
ListItem listItem = new ListItem();
listItem.Text = c.ToString();
listItem.Value = c.ToString();
if (SelectedValue == c.ToString())
{
listItem.Attributes.Add("class", "active");
}
_bulletList.Items.Add(listItem);
}
if (!this.Page.IsPostBack)
{
_bulletList.Items[0].Selected = true;
_bulletList.Items[0].Attributes.Add("class", "active");
}
this.Controls.Add(_bulletList);
}
private void BulletListItem_Click(object sender, BulletedListEventArgs e)
{
SelectedValue = SelectedText = _bulletList.Items[e.Index].Value;
SetActive(e.Index);
}
private void SetActive(int index)
{
if (this.Controls != null && ((BulletedList)this.Controls[0]).Items.Count > 0)
{
foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
{
listItem.Attributes.Clear();
}
}
((BulletedList)this.Controls[0]).Items[index].Attributes.Add("class", "active");
}
}
答案 0 :(得分:1)
添加以下代码:
protected override void CreateChildControls()
{
Controls.Clear();
CreateBulletedList();
}
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
更改SetSelected方法:
private void SetSelected()
{
foreach (ListItem listItem in _bulletList.Items)
{
if (listItem.Value == SelectedValue)
{
listItem.Attributes.Add("class", "active");
}
}
}