访问构造函数asp net中的WebControls可标记属性

时间:2012-11-16 16:14:49

标签: asp.net custom-server-controls

这是我的自定义控件。它继承了WebControl类的[Height]属性。我想在构造函数中访问它来计算其他属性。但是它的值总是为0.任何想法?

    public class MyControl : WebControl, IScriptControl
{

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

我的aspx

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

2 个答案:

答案 0 :(得分:3)

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

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

    base.OnInit(e);
}

答案 1 :(得分:1)

由于@andleer表示尚未在控件的构造函数中读取标记,因此在构造函数中无法使用标记中指定的任何属性值。在即将使用时按要求计算另一个属性,并确保在OnInit之前不要使用:

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