title: WPF Window.Close() not triggering UserControl.Unloaded event
body: <p>I have a Window that contains a custom UserControl.  The UserControl needs to know when the Window containing it has been closed so that it can terminate a thread.</p>
  
  <p>My best guess as to how to accomplish this is to handle the UserControl's Unloaded event.  However, the Unloaded event only seems to be firing when the user actually clicks to close the window, but not when I programmatically call the Close() method on the window.</p>
  
  <p>For reference sake, here are some of the relevant parts of my code.</p>
  
  <p>MyWindow.xaml:</p>
  
  <pre><code>&lt;Window x:Class="Namespace.MyWindow"
          xmlns:controls="clr-namespace:Namespace.Controls"&gt;
      &lt;controls:MyControl/&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>MyControl.xaml:</p>
  
  <pre><code>&lt;UserControl x:Class="Namespace.Controls.MyControl"
               Unloaded="UserControl_Unloaded"/&gt;
      &lt;!-- Stuff --&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p>MyControl.xaml.cs:</p>
  
  <pre><code>void UserControl_Unloaded(object sender, RoutedEventArgs e)
  {
      // Stop the thread.
  }
  </code></pre>
  
  <p>So just to recap, the UserControl_Unloaded() method above is getting called when I close the window "manually" (alt-F4, click the red "X", etc.), but not when from elsewhere in the code I call <code>myWindow.Close()</code>.  Any ideas?</p>