mrfangzheng

Hope and fear are useless. Be confident, and always be prepared for the worst.
  首页  :: 新随笔  :: 联系 :: 管理

C#: 根据事件名称动态添加事件

Posted on 2011-08-12 15:51  mrfangzheng  阅读(438)  评论(0编辑  收藏  举报
public static void BindCmdWithEventSrc(object eventSrc, string eventName, ICmd cmd)
{
    Action act 
= delegate
    {
    
if (cmd != null)
    {
        cmd.Execute();
    }
    };

    EventInfo ei 
= eventSrc.GetType().GetEvent(eventName);
    var handlerType 
= ei.EventHandlerType;
    var eventParams 
= handlerType.GetMethod("Invoke").GetParameters();
    
//lambda: (object x0, EventArgs x1) => d()       
    var parameters = eventParams.Select(p => Expression.Parameter(p.ParameterType, "x"));
    
// - assumes void method with no arguments but can be         
    
//   changed to accomodate any supplied method       
    var body = Expression.Call(Expression.Constant(act), act.GetType().GetMethod("Invoke"));
    var lambda 
= Expression.Lambda(body, parameters.ToArray());

    var del 
= Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke"false);
    ei.AddEventHandler(eventSrc, del);
}

public static void BindCmdWithEventSrc(object[,] bindings)
{
    
// bind control and command 
    for (int i = 0; i < bindings.GetLength(0); i++)
    {
    
object eventSrc = bindings[i, 0];
    
string eventName = bindings[i, 1as string;
    ICmd cmd 
= bindings[i, 2as ICmd;

    BindCmdWithEventSrc(eventSrc, eventName, cmd);
    }
}