简体   繁体   中英

How to create dynamic control event handler

I have problem with control event handler. I created a control ( button ) and I want to bind click event with a method. But I have "Error binding to target method." exception.

code is,

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;

                }
            }
        }
    }

}

so, what should I do?

thanks...

Your Sleep method signature isn't adequate to EventHandler delegate.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM