WPF:当窗口关闭时,从LostFocus处理程序调用TextBox.Clear()会导致NullReferenceEx



下面的示例有两个TextBox。第二个TextBox有一个LostFocus事件的处理程序,该事件本身调用Clear()。在两个文本框之间切换焦点效果良好;但是,如果窗口关闭时焦点在第二个文本框上,TextBox.Clear()将生成NullReferenceException。这是WPF中的一个错误吗?如何轻松检测这种情况,从而避免在窗口关闭时调用Clear()?

编辑:可能相关-该窗口是应用程序的主窗口。调用Clear()时,Test不为null。异常是从调用中的某个位置引发的。

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>

装配参考:

  • mscorlib,版本=2.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089
  • PresentationCore,版本=3.0.0.0,文化=中性,PublicKeyToken=31bf3856ad364e35
  • PresentationFrame,版本=3.0.0.0,文化=中性,PublicKeyToken=31bf3856ad364e35
  • 系统,版本=2.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089
  • WindowsBase,版本=3.0.0.0,区域性=中性,PublicKeyToken=31bf3856ad364e35

在触发LostFocus事件时,Test属性是否为null?

尝试:

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

编辑:我在用您发布的代码重现NullReferenceException时遇到问题。您使用的.NET版本是什么?

挂钩LostKeyboardFocus而不是LostFocus在我的情况下可以正常工作,并阻止事件处理程序抛出异常。

最新更新