Event fires more and more times

老子叫甜甜 提交于 2019-11-28 01:10:57

You can't use lambdas when you want to unregister from events.

this.globalEvents.OnSaveButtonClicked += (s, e) => SaveData(); 

This will create one instance - let's call it instance A - of type EventHandler and add it as a handler.

this.globalEvents.OnSaveButtonClicked -= (s, e) => SaveData(); 

This will not remove instance A from the event but create a new instance - instance B - and tries to remove it from the event.

To fix this problem, either create a little method or save that anonymous method in a field:

class ViewModel
{

    private EventHandler _saveButtonClickedHandler;
    // ...

    public ViewModel()
    {
        _saveButtonClickedHandler = (s, e) => SaveData();
        this.globalEvents.OnSaveButtonClicked += _saveButtonClickedHandler;
        // ...
    }

    public void Dispose()
    {
        this.globalEvents.OnSaveButtonClicked -= _saveButtonClickedHandler;
        // ...
    }

    // ...
}
this.globalEvents.OnSaveButtonClicked += (s, e) => SaveData();

This line is being called multiple times so you are adding a new event handler every time.

You need to either move that line to somewhere where it's only called once or change the event handler to:

this.globalEvents.OnSaveButtonClicked += SaveData;

public void SaveData(object sender, EventArgs e)  
{  
    globalEvents.RaiseSaveData(EditedGuy);     
    this.globalEvents.OnSaveButtonClicked -= SaveData();
}

So you remove the event handler after dealing with it. This assumes that the handler will be added back next time you go into edit mode.

You could define a private eventhandler delegate variable in your class and assign it in your constructor:

private SaveButtonClickedHandler _handler;

Assign the handler in your constructor:

_handler = (s,e) => SaveData();
this.globalEvents.OnSaveButtonClicked += _handler;

Dispose:

this.globalEvents.OnSaveButtonClicked -= _handler; 

"SaveButtonClickedHandler" is pseudo-code/placeholder for whatever the name of the delegate should be.

Hasanain

You'll have to put in a proper event handler method that calls SaveData() and register/unregister that. Otherwise you try to unregister another "new" anonymous method instead of the original one you've registered, which you, because it is anonymous, cannot actually access anymore.

public void SaveButtonClicked(object sender, EventArgs e)
{
    SaveData();
}

this.globalEvents.OnSaveButtonClicked += SaveButtonClicked;

this.globalEvents.OnSaveButtonClicked -= SaveButtonClicked;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!