Prevent next event handler being called

后端 未结 6 1197
孤街浪徒
孤街浪徒 2021-01-21 01:35

I have two event handlers wired up to a button click in a Windows form like so:

this.BtnCreate.Click += new System.EventHandler(new RdlcCreator().FirstHandler);
         


        
6条回答
  •  时光说笑
    2021-01-21 02:20

    System.ComponentModel namespace contains a CancelEventHandler delegate which is used for this purpose. One of the arguments it provides is a CancelEventArgs instance which contains a boolean Cancel property which can be set be any of the handlers to signal that execution of the invocation list should be stopped.

    However, to attach it to a plain EventHandler delegate, you will need to create your own wrapper, something like:

    public static class CancellableEventChain
    {
        public static EventHandler CreateFrom(params CancelEventHandler[] chain)
        {
            return (sender, dummy) =>
            {
                var args = new CancelEventArgs(false);
                foreach (var handler in chain)
                {
                    handler(sender, args);
                    if (args.Cancel)
                        break;
                }
            };
        }
    }
    

    For your example, you would use it like this:

    this.BtnCreate.Click += CancellableEventChain.CreateFrom(
        new RdlcCreator().FirstHandler,
        this.BtnCreate_Click
        /* ... */
    );
    

    Of course, you would need to capture the created chain handler in a field if you need to unsubscribe (detach) it later.

提交回复
热议问题