access WebControls markable properties in construc

2019-06-22 20:52发布

Here is my custom control.It inherits [Height] property from WebControl class.I want to access it in constructor for calculating other properties.But its value is always 0.Any idea?

    public class MyControl : WebControl, IScriptControl
{

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

my aspx

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

2条回答
Ridiculous、
2楼-- · 2019-06-22 21:09

Markup values are not available in your control's constructor but they are available from within your control's OnInit event.

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

    base.OnInit(e);
}
查看更多
够拽才男人
3楼-- · 2019-06-22 21:13

As @andleer said markup has not been read yet in control's constructor, therefore any property values that are specified in markup are not available in constructor. Calculate another property on demand when it is about to be used and make sure that you not use before OnInit:

private int fAnotherPropertyCalculated = false;
private int fAnotherProperty;
public int AnotherProperty
{
  get 
  {
    if (!fAnotherPropertyCalculated)
    {
       fAnotherProperty = Calculate(Height);
       fAnotherPropertyCalculated = true;
    }
    return fAnotherProperty;
  }
}
查看更多
登录 后发表回答