如何确定动态加载的usercontrol的类型?

时间:2008-12-09 01:08:39

标签: asp.net reflection user-controls

我有一个应用程序将根据用户动态加载usercontrols。您将在下面的示例中看到我通过switch / case语句转换每个用户控件。有一个更好的方法吗?反射? (我必须能够在每个控件中添加一个事件处理程序Bind。)

override protected void OnInit(EventArgs e)
{
    cc2007.IndividualPageSequenceCollection pages = new IndividualPageSequenceCollection().Load();
    pages.Sort("displayIndex", true);
    foreach (IndividualPageSequence page in pages)
    {
        Control uc = Page.LoadControl(page.PageName);
        View view = new View();
        int viewNumber = Convert.ToInt32(page.DisplayIndex) -1;

        switch(page.PageName)
        {
            case "indStart.ascx":
                IndStart = (indStart) uc;
                IndStart.Bind += new EventHandler(test_handler);
                view.Controls.Add(IndStart);
                MultiView1.Views.AddAt(viewNumber, view);
                break;

            case "indDemographics.ascx":
                IndDemographics = (indDemographics)uc;
                IndDemographics.Bind += new EventHandler(test_handler);
                view.Controls.Add(IndDemographics);
                MultiView1.Views.AddAt(viewNumber, view);
                break;

            case "indAssetSurvey.ascx":
                IndAssetSurvey = (indAssetSurvey)uc;
                IndAssetSurvey.Bind += new EventHandler(test_handler);
                view.Controls.Add(IndAssetSurvey);
                MultiView1.Views.AddAt(viewNumber, view);
                break;
        }

    }
    base.OnInit(e);
}

提前致谢!

4 个答案:

答案 0 :(得分:1)

怎么样:

Type t = uc.GetType();
EventInfo evtInfo = t.GetEvent("Bind");
evtInfo.AddEventHandler(this, new EventHandler(test_handler));

我没有测试过这段代码,但应该是这样的。

答案 1 :(得分:1)

我的代码中没有看到任何特定于控件类的内容。您执行完全相同的操作,看起来所有用户控件都从Control继承。

如果唯一特定的事情是事件绑定(即Control类没有Bind事件),那么最好考虑重构代码,这样就可以使所有用户控件继承如下:Control - > MyBaseControl(把事件放在这里) - > YouControl。

如果您无法控制控件的来源,那么Jeroen建议应该有效。

答案 2 :(得分:1)

如何使用Bind事件定义接口并让控件实现它?

public interface IBindable
{
  event EventHandler Bind;
}

然后:

foreach (IndividualPageSequence page in pages)
{
  IBindable uc = Page.LoadControl(page.PageName) as IBindable;
  if( uc != null )
  {
    uc.Bind += new EventHandler(test_handler);
    View view = new View();
    view.Controls.Add(page);
    int viewNumber = Convert.ToInt32(page.DisplayIndex) -1;
    MultiView1.Views.AddAt(viewNumber, view);
  }
}

答案 3 :(得分:0)

您可以尝试TypeOf(在c#中)或者uc.GetType()可以工作。

相关问题