WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法
在WPF的TextBox的LostFocus事件中直接使用Focus()方法会出现死循环的问题
正确的使用方式有2中方法:
方法一:
- private void textBox3_LostFocus(object sender, RoutedEventArgs e)
{
if (textBox3.Text != "abc")
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render,
new Action(() =>
{
textBox3.Focus();
}));
}
}
方法二,使用LostKeyboardFocus方法:
- private void textBox3_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (textBox3.Text != "abc")
{
textBox3.Focus();
}
}