如何创建动态控件事件处理程序

时间:2009-11-03 11:26:30

标签: c# dynamic controls event-handling

我遇到控件事件处理程序的问题。我创建了一个控件(按钮),我想用一个方法绑定click事件。但我有“绑定到目标方法的错误。”异常。

代码是,

class SetControlEvent
{

    public void Sleep()
    {
        System.Threading.Thread.Sleep(5000);
    }

    internal void Set(object theObject,XmlNode theControlNode)
    {
        EventInfo ei = theObject.GetType().GetEvent("Click");


        EventDescriptorCollection events = TypeDescriptor.GetEvents(theObject);
        foreach (EventDescriptor theEvent in events)
        {
            foreach (XmlAttribute attribute in theControlNode.Attributes)
            {
                if (theEvent.DisplayName == attribute.Name)
                {

                    MethodInfo mi = typeof(SetControlEvent).GetMethod("Sleep");
                    Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, "Sleep");

                    theEvent.AddEventHandler(theObject, del);



                    break;

                }
            }
        }
    }

}

所以,我该怎么办?

感谢...

1 个答案:

答案 0 :(得分:1)

Sleep方法签名不足以EventHandler委托。

试试这个:

    public void Sleep(Object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(5000);
    }