【问题标题】:Dynamic events in a UserControlUserControl 中的动态事件
【发布时间】:2011-05-15 07:44:43
【问题描述】:

我使用 GUI 创建了一个自定义 UserControl,但我无法让它接受自定义类中动态添加的事件。 对不起,如果我从记忆中弄错了确切的代码,但你明白了要点。 C# .NET 2008,Winform

我有一个“容器类”来存储我的所有信息。
主 WinForm 有一个数组,每个都有一个摘要面板。 主窗体还有一个“工作区”,可让您访问容器类。

这个想法是,与 CustomUserControl 交互会导致 ContainerClass 中发生一些事情。该控件使用那里的信息,我希望它从那里更新。

ContainerClass
{
    CustomUserControl tempControl;
    public ContainerClass()
    {
        //do stuff
        tempControl = new CustomUserControl([send information]);
        tempControl.Click += new Event(localClickEvent);
    }

    public void localClickEvent(object sender, Event e)
    {
        //do stuff
    } 
}

.

public class Form1
{
    public Form1()
    {
        //create several container objects
        //for each container object, get it's SummaryPanel 
        //and add it to the FlowLayoutPanel
        CustomUserControl tempControl = ContainerObject.GetCustomControl();
        flp_summaryPanel.Controls.Add(tempControl);
    }
}

当我执行这段代码时,动态事件永远不会触发。 我以前做过这种事情,但总是使用继承了我需要的控件的自定义类。我从来没有继承过 UserControl,所以我怀疑我遗漏了一些东西。 我怀疑这是一个保护问题,但编译器没有发现它。

更多信息

这不知何故被标记为 ASP.net 问题。不是,我用的是 Winforms,虽然我从来没有明确说过。

另一件可能很重要的事情:动态事件不在另一个控件中。它位于一个自定义类中,用作大型容器对象。

。 .

一如既往,非常感谢您的帮助! :)

【问题讨论】:

    标签: c# .net winforms user-controls dynamic


    【解决方案1】:

    在将控件添加到Controls 集合后尝试附加事件处理程序

    public ParentControl()
    {
        CustomUserControl tempControl = new CustomUserControl();
        this.Controls.Add(tempControl);
        tempControl.Click += new Event(localClickEvent);
    }
    

    这可能与除非将控件添加到 NamingContainer 否则无法正确生成 ClientID 的事实有关。

    【讨论】:

      【解决方案2】:

      您使用的是哪个版本的 C#?试试这个:

      public void ParentControl_Init()
      {
          CustomUserControl tempControl = new CustomUserControl(); 
          this.Controls.Add(tempControl); 
          tempControl.Click += localClickEvent; 
      }
      
      public void localClickEvent(object sender, EventArgs e) 
      { 
          //do stuff 
      }  
      

      您不想在构造函数中添加控件和附加事件。看看 ASP.NET 是如何做到的,你就会明白为什么。

      【讨论】:

      • 为什么不想在构造函数中添加事件?这就是调用 InitializeComponent 时发生的情况。
      • 您使用的是哪个版本的 ASP.NET?他们不再做 InitializeComponent 了。
      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多