dev
dev

Reputation: 11

How to dispose off the relay command in mvvm wpf model

I have this app using MVVM wpf model along with John Smith's relay command class. There are two main issues with it:

  1. Even after disposing the view model and setting the commands to null, they are still fired afterwards.

  2. The view model although disposed off, still seems to be in memory. It's using tab control on top and the memory never gets cleaned even after closing the tabs. This is related to the view model since once the properties of the view model are set to null, the next time you open a different tab the view model tries to access the property that was disposed off. FYI there are no singletons involved here.

It is using the relay command class and the problem eventually lies here where the commands are being fired even though the target object has not raised it i.e. the button a command is linked to is not clicked but still it fires it when closing its child window.

Upvotes: 1

Views: 3009

Answers (1)

agent-j
agent-j

Reputation: 27913

Raise the PropertyChanged event for the command properties after you set them to null.

public class ViewModel : INotifyPropertyChanged, IDisposable
{
   public event PropertyChangedEventHandler PropertyChanged;
   public void Dispose()
   {
      Command = null;
   }

   public RelayCommand Command
   {
      get{return m_command;}
      set
      {
         if(m_command == value)
            return;
         m_command = value;
         if (PropertyChanged != null)
            PropertyChanged (this, new PropertyChangedEventArgs ("Command");
      }
   }
}

Upvotes: 1

Related Questions