WPF:从引发LostFocus处理程序调用TextBox.Clear()引起的NullReferenceException当窗口关闭

问题描述 投票:1回答:2

下面的示例具有两个文本框。第二个文本框有其自身调用清除()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>

集引用:

  • mscorlib程序,版本= 2.0.0.0,文化=中性公钥= b77a5c561934e089
  • PresentationCore,版本= 3.0.0.0,文化=中性公钥= 31bf3856ad364e35
  • PresentationFramework,版本= 3.0.0.0,文化=中性公钥= 31bf3856ad364e35
  • 系统,版本= 2.0.0.0,文化=中性公钥= b77a5c561934e089
  • WindowsBase,版本= 3.0.0.0,文化=中性公钥= 31bf3856ad364e35
wpf
2个回答
2
投票

可以在测试属性为空的时候LostFocus事件被解雇?

尝试:

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

编辑:我无法重现与您发布的代码的NullReferenceException。哪个版本的.NET您使用的是?


1
投票

挂钩LostKeyboardFocus而不是引发LostFocus工程确定为我的情况和停止的事件处理程序抛出异常。

© www.soinside.com 2019 - 2024. All rights reserved.