因事件而改变内部控制

时间:2019-02-20 08:49:38

标签: c# asp.net data-binding controls page-lifecycle

我有一个复合控件,如:

class MyControl : CompositeControl {
   private Control _control1;
   private Control _control2;

   public bool RenderControl2 { get; set; }

   /* Constructor to initialize controls*/

    protected override void CreateChildControls(){
       if(RenderControl2){
           Controls.Add(_control2);
       }else{
           Controls.Add(_control1);
       }           
    }        
}

在Page_Init()期间设置RenderControl2的值的情况下,此方法很好用。

 protected void Page_Init(object sender, EventArgs e){
    if (!Page.IsPostBack){
       myControl.RenderControl2 = MyMagicFucntion();
    }
    /* Works also when in Postback, but not required since the control keeps it state and only need to change state in the scenario below.*/
}

但是,现在我们要根据事件来设置值

protected void otherDropDow_SelectedIndexChanged(object sender, EventArgs e) {
    myControl.RenderControl2 = otherDropDown.SelectedValue == "My Magic String";
}

这不起作用,因为控件在事件触发时已经执行了CreateChildControls。 (嗯,它在下一次回发时确实起作用... :()

我试图将逻辑移至控件的OnDataBinding事件。但这似乎对控件在页面上的实际显示方式没有影响。

/* DOES NOT RESOLVE THE ISSUE */
protected override void OnDataBinding(EventArgs e){  
   base.OnDataBinding(e);
   /* _renderControl2HasChanged is set when RenderControl2 changes value          
   */
   if(_renderControl2HasChanged)
      if(RenderControl2){
          Controls.Remove(_control1);
          Controls.Add(_control2);
      }else{
          Controls.Remove(_control2);
          Controls.Add(_control1);
      }
   }      

1 个答案:

答案 0 :(得分:1)

您无需决定要在public static class API { private static System.Net.Http.HttpClient httpClient; public static System.Net.Http.HttpClient Instance { get { return httpClient ?? (httpClient = new System.Net.Http.HttpClient()); } } } public static async Task<string> GetData(string id) { HttpResponseMessage response = await API.Instance.GetAsync(string.Format(requestURL, id)); response.EnsureSuccessStatusCode(); // return URI of the created resource. return await response.Content.ReadAsStringAsync(); } 中显示哪个控件,而是可以评估CreateChildControls中的标志,而仅更改子控件的可见性,例如:

OnPreRender

此外,您应按照there的描述将protected override void CreateChildControls() { Controls.Add(_control1); Controls.Add(_control2); } protected override void OnPreRender(EventArgs e) { _control1.Visible = !RenderControl2; _control2.Visible = RenderControl2; } 的值保存在控制状态中。这样,它将在回发之间保持不变。