myermian
myermian

Reputation: 32515

Need to create an event handler that can remove itself when the event occurs

I'm not really sure how to do this, as I've never had a need for this pattern just yet. I'm looking for the correct pattern on creating an event handler in a separate class that can remove itself when the object that contains the event executes.

Basically, I want to create an EventHandler that occurs on the WPF Window.Close event. And, during the execution of the handler it removes itself from the Window.Close event. I hope that's specific enough to go on.

Also, is there a specific name for this pattern?

Upvotes: 3

Views: 2849

Answers (3)

GameAlchemist
GameAlchemist

Reputation: 19294

Please tell more about the 'what' of your project : what do you intend to do.
Maybe you would be interested in manual reset event, that triggers only once unless you reset them : http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx

Upvotes: 1

RredCat
RredCat

Reputation: 5421

Try to do something like next:

 RoutedEventHandler handlerLoad = null;
 handlerLoad = delegate
        {
            //Do something
            Window.Close -= handlerLoad;
        };

Window.Close += handlerLoad;

Upvotes: 15

DaveDev
DaveDev

Reputation: 42185

would something like the following work?

public void EventHandlerSubscription_Invoked(object sender, EventArgs args)
{
    _objectContainingEvent.MyEventHandler -= EventHandlerSubscription;
}

Sorry if this isn't sensible, I'm typing off the top of my head.

Upvotes: 2

Related Questions