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">
<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