扩展控件——自定义属性

给控件自定义属性,一般情况:方式1
public class CustomControl:WebControl
{
  private string _customProperty;
  public string CustomProperty
  {
    get { return _customProperty;}
    set{ customProperty=value;}
  }
}
  最近也在简单重写一些控件属性,发现了一些问题,如上所述的自定义属性有一点缺陷:
因为.net控件都会有个__DoPostBack问题,所以当这个属性不是在html页面上写死的值,而是在后台动态赋值的情况下
会出现重新初始化。
  我重写了GridView分页标签,后台给CustomPagerSettings.TextData=“每页{0}条/共{1}条        第{2}页/共{3}页    ”,
然后GridView有个子表功能;现在问题出现在子表的翻页上:因为子表翻页不会重新绑定父表,所以父表结构不会变化,但子表翻页
会刷新页面,CustomPagerSettings.TextData会被置空<后台CustomPagerSettings.TextData的赋值语句放在Page_Load()中
仍然不行>,跟踪程序后发现,子表分页函数执行后,父表分页标签会执行一个onchange()事件,然后重构分页标签CustomPagerSettings.TextData的值此时是空。

网上找到另一种定义方式:方式2
public class CustomControl:WebControl
{
  public string CustomProperty
  {
    get
            {
                return this.GetPropertyValue("CustomProperty ", string.Empty);
            }
            set
            {
                this.SetPropertyValue("CustomProperty ", value);
                this.textbox.ID = value;
            }
  }

   public T GetPropertyValue<T>(string propertyName, T nullValue)
        {
            if (this.ViewState[propertyName] == null)
            {
                return nullValue;
            }
            return (T)this.ViewState[propertyName];
        }

        public void SetPropertyValue<T>(string propertyName, T value)
        {
            this.ViewState[propertyName] = value;
        }
}
中定义将赋值存储在Viewstate中,不会出现上述重构时没值的情况了。
注:我在重写时用上述方法仍然行不通,经过仔细调试发现问题。扩展的属性如果是直接写在CustomControl类中用方式2没有问题。
但是可能扩充的是一个附加类属性,比如
public class CustomControl:WebControl
{
 private CustomProperty _newProperty; 
  ...
}
public class CustomProperty
{
  public string CustomProperty {get;set;}
}
这种情况在CustomProperty类中是无法按照方式2定义的,因为viewstate是WebControl的特性,所以要记住只有继承了WebControl的
类才可以。 CustomProperty类如果继承WebControl也是不行的,只有CustomControl类的viewstate记住属性值才有效果。
原文地址:https://www.cnblogs.com/maomaokuaile/p/1574966.html