using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
[ParseChildren(true, "Content")]
public class ScrollSaverPanel: WebControl
{
[TemplateInstance(TemplateInstance.Single)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ITemplate Content { get; set; }
private HiddenField HiddenField { get; set; }
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
protected override void OnInit(EventArgs e)
{
HiddenField = new HiddenField();
var metaContainer = new WebControl(HtmlTextWriterTag.Div);
metaContainer.Controls.Add(HiddenField);
metaContainer.Style.Add(HtmlTextWriterStyle.Display, "none");
Controls.Add(metaContainer);
var contentContainer = new WebControl(HtmlTextWriterTag.Div);
Controls.Add(contentContainer);
Content.InstantiateIn(contentContainer);
this.Style.Add(HtmlTextWriterStyle.Overflow, "auto");
this.Attributes.Add("onscroll", string.Format("javascript:document.getElementById('{0}').value = this.scrollTop;", HiddenField.ClientID));
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "setscroll", string.Format("javascript:document.getElementById('{0}').scrollTop = '{1}';", this.ClientID, HiddenField.Value), true);
base.OnPreRender(e);
}
}
用法:
<general:ScrollSaverPanel runat="server">
<Content>
<stwrw:Group runat="server" ID="rootGroup"/>
</Content>
</general:ScrollSaverPanel>
由于有些人不想仅出于保存滚动位置的目的而使用更新面板... :)