【问题标题】:access WebControls markable properties in constructor asp net在构造函数asp net中访问WebControls可标记属性
【发布时间】:2012-11-05 09:34:00
【问题描述】:

这是我的自定义控件。它从 WebControl 类继承 [Height] 属性。我想在构造函数中访问它以计算其他属性。但它的值始终为 0。知道吗?

    public class MyControl : WebControl, IScriptControl
{

    public MyControl()
    {
       AnotherProperty = Calculate(Height);
       .......
    }

我的 aspx

       <hp:MyControl   Height = "31px" .... />  

【问题讨论】:

    标签: asp.net custom-server-controls


    【解决方案1】:

    标记值在控件的构造函数中不可用,但在控件的 OnInit 事件中可用。

    protected override void OnInit(EventArgs e)
    {
        // has value even before the base OnInit() method in called
        var height = base.Height;
    
        base.OnInit(e);
    }
    

    【讨论】:

    • 但是如何在 GetScriptDescriptors() 方法中访问高度?
    • 你的意思是我必须将高度保存在其他变量中吗? this.U = base.Height;
    • 我并没有完全按照您的想法进行操作,并且对IScriptControl 界面一无所知。
    • 不确定将其保存在不同的变量中会改变事情。从“基础”对象中引用它比其他任何东西都更像是一种约定/最佳实践。如果您没有名为 Height 的本地成员,则不必区分它们。在您的问题中包含更多源代码可能会有所帮助。
    【解决方案2】:

    正如@andleer 所说,尚未在控件的构造函数中读取标记,因此在标记中指定的任何属性值在构造函数中均不可用。在即将使用时按需计算另一个属性,并确保在 OnInit 之前不要使用:

    private int fAnotherPropertyCalculated = false;
    private int fAnotherProperty;
    public int AnotherProperty
    {
      get 
      {
        if (!fAnotherPropertyCalculated)
        {
           fAnotherProperty = Calculate(Height);
           fAnotherPropertyCalculated = true;
        }
        return fAnotherProperty;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2012-07-06
      • 2019-05-21
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2017-03-22
      • 1970-01-01
      相关资源
      最近更新 更多