从Textbox发送输入

时间:2012-12-21 09:20:43

标签: textbox user-input

我的C#WPF项目上有一个文本框,我想让它在输入后将输入到文本框中的值发送到以下函数中。

我的文本框中的用户输入是否必须在一个单独的函数中,或者我可以在我希望将值发送到的同一函数中使用它吗?

    private void UserInput(object sender, KeyEventArgs e)
    {
        Point p1 = new Point();
        TextBox textBoxX = new TextBox();
        if (e.Key == Key.Enter)
        {
            double inputAsNumberX = 0.0000;
            if (double.TryParse(textBoxX.Text, out inputAsNumberX))
            {
                p1.X = inputAsNumberX;
            }
            else
            {
                MessageBox.Show("This is not a number.");
            }

        }
        else
        {
        }

        double inputAsNumberY = 0;
        TextBox textBoxY = sender as TextBox;
        while (textBoxY.Text == null)
        {
            //textBoxY = sender as TextBox;
        }
        if (double.TryParse(textBoxY.Text, out inputAsNumberY) == true)
        {
            p1.X = inputAsNumberY;
        }
        else
        {
            MessageBox.Show("This is not a number.");
        }


    } 

xaml代码

<TextBox Name="TextBoxX" TextWrapping="Wrap" MaxLength="32" KeyDown="UserInput" />

更新:奇怪的是我有一个问题是当我尝试输入任何东西(在调试时),它阻止我输入任何东西。在运行代码并尝试再次输入后,它允许我输入一个字符(如数字),然后阻止我输入更多字符。

它似乎也只显示代码运行后在文本框中键入的新char。

如何修复我的代码以运行我想要的方式,即输入一个值,按回车键,将值发送到函数,将其设置为double变量:inputAsNumberX ???

更新2: 我已经更新了我正在使用的代码。我想获得两个输入,所以我设置了两个文本框。两者都应该像我上面提到的那样做。

1 个答案:

答案 0 :(得分:0)

据我所知,您已将UserInput函数设置为文本框上KeyDown事件处理程序的处理程序。这意味着每次按下选择了文本框的键时,都会调用UserInput函数。如果您只想在按下“Enter”时解析文本框的内容,则可以将代码更改为以下内容:

private void UserInput(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        var textBox = sender as TextBox;
        if (textBox != null)
        {
            double inputAsNumberX = 0;

            if (double.TryParse(textBox.Text, out inputAsNumberX))
            {
                // Do something with inputAsNumberX here.
            }
            else
            {
                MessageBox.Show("This is not a number.");
            }
        }
    }
}

请注意,我首先检查是否按下了'Enter'。

<强>更新

我更改了上面的代码,以便它可以使用UserInput作为KeyDown事件的事件处理程序的任何文本框。对以下两个文本框使用以下XAML:

<TextBox Name="TextBoxX" TextWrapping="Wrap" MaxLength="32" KeyDown="UserInput" />
<TextBox Name="TextBoxY" TextWrapping="Wrap" MaxLength="32" KeyDown="UserInput" />