title: WPF: Calling TextBox.Clear() from LostFocus handler causes NullReferenceException when window closes
body: <p>The sample below has two TextBoxes.   The second TextBox has a handler for the LostFocus event which calls Clear() on itself.  Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException.  Is this a bug in WPF?  How can I easily detect this situation so I can avoid calling Clear() when the window is closing?</p>
  
  <p>Edit: Possibly relevant - The window is the application's main window.  Test is not null at the time Clear() is called.  The exception is thrown from somewhere within the call.</p>
  
  <pre><code>using System.Windows;
  
  namespace TextBoxClear
  {
      public partial class Window1 : Window
      {
          public Window1()
          {
              InitializeComponent();
          }
  
          private void Test_LostFocus(object sender, RoutedEventArgs e)
          {
              Test.Clear();
          }
      }
  }
  
  
  &lt;Window x:Class="TextBoxClear.Window1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
      &lt;StackPanel&gt;
          &lt;TextBox /&gt;
          &lt;TextBox LostFocus="Test_LostFocus" Name="Test" /&gt;
      &lt;/StackPanel&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>Assembly references:</p>
  
  <ul>
  <li>mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li>
  <li>PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li>
  <li>PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li>
  <li>System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li>
  <li>WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li>
  </ul>