Reputation: 4523
that is a question I have been asking myself for a while.
Giving a certain flow of events, can I when handling one of them, stop the next ones to be raised?
For example, when collapsing a node which child was selected in a treeview (winform), the events are raised like that:
I could stop them by using a class member, but I was wondering whether there was a built-in function or just another way (a more elegant way) to achieve this, by acting directly on the events queue.
Any idea?
Upvotes: 1
Views: 1579
Reputation: 19064
The only times you can easily "cancel" an event is if the event handler has the CancelEventHandler
delegate type. Even then it doesn't really cancel it as much as set a flag for the remaining events that makes it skip performing all the events subscribed to it.
If you did have a CancelEventHandler
type (which these don't) you'd simply set Cancel
to true on the event object itself in the handler.
Plenty of other answers give you suggestions for what you should o. I'd just go with your idea: set a 'event cancelled' flag in your control class, and check it. When the last event in the series gets called, reset it.
Upvotes: 0
Reputation: 10940
according to OnBeforeCollapse you get an TreeViewCancelEventArgs which has an Cancel
property. Setting this to true should stop the flow, but will also not collapse it.
Same goes for OnBeforeSelect
.
Upvotes: 0
Reputation: 7200
Not easily, no. The order of the events firing is controlled by the TreeView control class, and there is no built-in way to prevent events from firing. But you have a couple of options:
bool
property to prevent the events from processing.
Then you can override BeforeCollapse
, etc. to check the bool
before calling base.BeforeCollapse
. bool
flag, and check the flag in each of the events.Upvotes: 1
Reputation: 26737
even if the event are raised nothing will happen if you don't bind an event handler to them. In this case you can just remove the handler using the code below:
object.Event -= new EventHandlerType(your_Method)
Otherwise you should create your own custom control
Upvotes: 0
Reputation: 62256
No there is no way to do that for that type of event (you are asking for TreeView).
Like for example could be managed KeyEventArgs.Handled via built-in mechanism.
You can use some instance (boolean ?) value to manage the flow,
or you can, unsubscribe from the event that you don't want more recieve, but after subscribe to it again. Sounds rough solution, but sometimes turns out reasonable one.
Upvotes: 0