下面的示例具有两个文本框。第二个文本框有其自身调用清除()LostFocus事件的处理程序。两个文本框之间切换焦点正常工作;然而,如果焦点在第二个文本框关闭时的窗口中,TextBox.Clear()生成一个NullReferenceException。这是WPF的错误吗?我怎么能轻易检测到这种情况,所以我可以避免调用清除()当窗口被关闭?
编辑:可能相关 - 该窗口是应用程序的主窗口。测试是不是在时间清除()被调用空。唯一的例外是从电话中的某处抛出。
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>
集引用:
可以在测试属性为空的时候LostFocus事件被解雇?
尝试:
private void Test_LostFocus(object sender, RoutedEventArgs e)
{
if (Test != null)
Test.Clear();
}
编辑:我无法重现与您发布的代码的NullReferenceException。哪个版本的.NET您使用的是?
挂钩LostKeyboardFocus而不是引发LostFocus工程确定为我的情况和停止的事件处理程序抛出异常。