Event fires more and more times

前端 未结 4 2070
余生分开走
余生分开走 2020-12-06 18:40

I have a silverlight mvvm application that loads main view with 2 user controls loaded into 2 ContentControls, one with listbox showing items and other with edit button. Whe

4条回答
  •  时光取名叫无心
    2020-12-06 19:11

    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;
            // ...
        }
    
        // ...
    }
    

提交回复
热议问题