扩展控件——自定义属性

给控件自定义属性,一般情况:方式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/archive/2009/09/27/1574966.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值