tags:

views:

2006

answers:

2

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?

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.

Thanks, Dave

using System.Windows;

namespace TextBoxClear
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Test_LostFocus(object sender, RoutedEventArgs e)
        {
            Test.Clear();
        }
    }
}


<Window x:Class="TextBoxClear.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <StackPanel>
        <TextBox />
        <TextBox LostFocus="Test_LostFocus" Name="Test" />
    </StackPanel>
</Window>

Assembly references:

  • mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
  • PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  • PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  • System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
  • WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
+2  A: 

Could the Test property be null by the time the LostFocus event is fired?

Try:

    private void Test_LostFocus(object sender, RoutedEventArgs e)
    {
        if (Test != null)
            Test.Clear();
    }

EDIT: I'm having trouble reproducing the NullReferenceException with the code you posted. Which version of .NET are you using?

Jason Anderson
Likewise, I can't reproduce the error. I've added an additional debug statement to the window close event, and it definitely fires after the text box lost focus, so I doubt that's causing the problem.
Darksider
+1  A: 

Hooking LostKeyboardFocus instead of LostFocus works OK for my situation and stops the event handler throwing exceptions.