title: WPF disposing of view and viewmodel correctly
body: <p>I've written an Outlook add-in (OL2010). It has a menu on the ribbon bar with various icons that open new windows that do stuff (hope that's not too in-depth ;)).  An example of one of the icon <code>Click</code> handlers is below.</p>
  
  <pre><code>public void OnViewMyTracksClick(Office.IRibbonControl control)
  {
      try {
      MyTracksViewModel viewModel = new MyTracksViewModel();
      MyTracksView view = new MyTracksView();
      view.DataContext = viewModel;
      view.Show();
      }
      catch (Exception ex)
      {
          Log.Error("xxxxx", "Error on button click: " + ex.Message + Environment.NewLine + ex.InnerException);
      }
  }
  </code></pre>
  
  <p>In Outlook, if I click the button to open this view, I see the memory usage of <code>Outlook.exe</code> increase by 10mb (the window and it's accompanying data). When I close the view, none of that memory is reclaimed. If I click the button again, another 10mb is added, and again, none is released when I close the view.</p>
  
  <p>I thought that this is because I'm creating a new viewmodel everytime, so I added some code to check if it was already instantiated (the view and viewmodel are now registered at the class level, rather that within the method, so that I don't create a new one each time) - <code>_allTracksVM</code> is an instantiation of <code>AllTracksViewModel</code>. <code>_allTracksV</code> is the view.</p>
  
  <pre><code>public void OnViewAllTracksClick(Office.IRibbonControl control)
  {
      try {
          if (_allTracksVM == null)
          {
              _allTracksVM = new AllTracksViewModel();
  
          }
          _allTracksV = new AllTracksView();
          _allTracksV.DataContext = _allTracksVM;
          _allTracksV.Show();
      }
      catch (Exception ex)
      {
          Log.Error("xxxxx", "Error on button click: " + ex.Message + Environment.NewLine + ex.InnerException);
      }
  }
  </code></pre>
  
  <p>This didn't seem to make any difference. I then added an <code>EventHandler</code> that would fire when the view was closed:</p>
  
  <pre><code>_allTracksV.Closing += new System.ComponentModel.CancelEventHandler(this.view_RequestClose);
  </code></pre>
  
  <p>And this set both the objects to null (you can probably tell i'm grabbing at straws at this point):</p>
  
  <pre><code>void view_RequestClose(object sender, EventArgs e)
  {
      _allTracksVM = null;
      _allTracksV = null;
  }
  </code></pre>
  
  <p>The memory remains allocated. How can I dispose of the objects correctly (or perhaps I should be instantiating them differently), so that they don't consume another chunk of memory each time they are opened?</p>
  
  <p>Thanks</p>
  
  <p>Mick</p>