0

我正在尝试解决以下问题:

我有一个需要在另一个控件中动态加载的用户控件。这个动态加载的控件引发了一个事件,据我所知,只有在 onload 事件期间创建和加载控件时,动态加载的控件引发的事件才会被正确处理。在动态加载控件时,我还必须考虑一个约束,这是父控件中的一个属性。此属性将确定是否应加载控件。

伪代码:

ControlA
  Property ShowControl
  ControlA has a CheckBox(chkShowControlIfSelected)
  OnLoadEvent()
    If chkShowControlIfSelected.checked checked and ShowControlProperty is set
    {
       reate ControlB Dynamically
       ControlB.Event += EventHandler()
       Add ControlB to ControlCollection
    }

我遇到的问题是,如果我在 prerender 事件中包含加载 controlB 的代码,则属性 ShowControl 设置正确,但未调用 EventHandler()。如果我将代码放入 pageLoad 事件中动态加载 controlB,则尚未设置属性 ShowControl,但在这种情况下,正确调用了 eventHandler 代码。

我是否遗漏了某些东西或在不正确的事件处理程序中处理代码?

4

1 回答 1

1

以下是工作示例:

控制A:

public partial class ControlA : System.Web.UI.UserControl
{
    public bool ShowControl
    {
        get
        {
            if (this.ViewState["ShowControl"] == null)
                return false;
            else
                return (bool)this.ViewState["ShowControl"];
        }
        set
        {
            this.ViewState["ShowControl"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.ShowControl)
        {
            var controlB = (ControlB)this.LoadControl("ControlB.ascx");
            controlB.FileUploadingComplete += controlB_FileUploadingComplete;
            this.pnl1.Controls.Add(controlB);
        }
    }

    void controlB_FileUploadingComplete(object sender, EventArgs e)
    {
        //throw new NotImplementedException();
        Trace.Write("file upload completed");
    }
}

控制B:

public partial class ControlB : System.Web.UI.UserControl
{
    public event EventHandler FileUploadingComplete;
    protected void OnFileUploadingComplete()
    {
        if (this.FileUploadingComplete != null)
            this.FileUploadingComplete(this, EventArgs.Empty);
    }

    protected void btn1_Click(object sender, EventArgs e)
    {
        this.OnFileUploadingComplete();
    }
}

页面(已ControlA存在):

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.ControlA1.ShowControl = true;
    }
}
于 2014-05-13T19:16:22.873 回答