想知道TextBox方法 [英] Wondering about TextBox methods

查看:135
本文介绍了想知道TextBox方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextBox,我想根据输入的是否为整数来经历一些条件.我的操作是从TextBox所在窗口的代码后面进行的.

I have a TextBox for which I would like to run through a few conditions based on whether or not there is an integer entered in it. My operations take place from the code-behind of the window that the TextBox exists in.

LostFocus事件下,我想执行以下操作:

Under the LostFocus event I would like to do the following:

  • 检查string IsNullOrEmpty

-如果是-将文本设置为默认记录"

-If it is - set text to "Default Record"

验证输入的值是Int

如果不是,请显示MessageBox(Ok Button),然后将焦点重新置于TextBox

If it isn't - Display a MessageBox(Ok Button), then set focus back on the TextBox

**这是我的LostFocus函数的外观:

**This is what my LostFocus function looks like:

private void TextBox_LostFocus(object sender, RoutedEventArgs e) //Lost Focus
{
    if (string.IsNullOrEmpty(TextBox.Text))
        TextBox.Text = "Default Record";
    else if (Regex.IsMatch(TextBox.Text, @"^\d+$") == false)
    {
        MessageBox.Show("Illegal character in list.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
        TextBox.Focus();
    }
}

以上功能对于测试string IsNullOrEmpty是否很好,但是else if条件存在问题.当我尝试将焦点重设回TextBox时,我得到一个无限循环的MessageBoxes.为什么会这样,我该如何解决?

The above function works well for testing whether or not the string IsNullOrEmpty, but I'm having problems with the else if condition. When I try to reset the focus back onto the TextBox I get an endless loop of MessageBoxes. Why is this and how do I fix it?

更新1:

这些是TextBox上的其他事件处理程序:

These are additional event handlers on the TextBox:

//State of View at startup
private void Document_Loaded(object sender, RoutedEventArgs e)
{
    //This is run because I need the TextBox to have focus at window startup
    TextBox.Focusable = true;
    TextBox.Focus();
}

xaml:

<UserControl Loaded="Document_Loaded" ... >

推荐答案

请勿尝试在Enter,GotFocus,Leave, LostFocus,Validating或Validated事件处理程序.这样做可能会导致 您的应用程序或操作系统停止响应...

Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding...

来自 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆