从 WPF 应用程序中的文本框获取用户输入 [英] Get user input from a textbox in a WPF application

查看:48
本文介绍了从 WPF 应用程序中的文本框获取用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我正在构建的 WPF 应用程序中的文本框中获取用户输入.用户将输入一个数值,我想将它存储在一个变量中.我刚刚开始使用 C#.我该怎么做?

I am trying to get user input from the textbox in a WPF application I am building. The user will enter a numeric value and I would like to store it in a variable. I am just starting on C#. How can I do it?

目前我正在打开文本框并让用户输入值.之后,用户必须按下一个按钮,将文本框中的文本存储在一个变量中.

Currently I am opening the textbox and letting the user enter the value. After that the user has to press a button upon which the text from textbox is stored in a variable.

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    var h = text1.Text;
}

我知道这是不对的.什么是正确的方法?

I know this isn't right. What is the right way?

推荐答案

就像@Michael McMullin 已经说过的,你需要像这样在函数外定义变量:

Like @Michael McMullin already said, you need to define the variable outside your function like this:

string str;

private void Button_Click(object sender, RoutedEventArgs e)
{
    str = text1.Text;
}

// somewhere ...
DoSomething(str);

重点是:变量的可见性取决于它的作用域.请看一下这个解释.

The point is: the visibility of variable depends on its scope. Please take a look at this explanation.

这篇关于从 WPF 应用程序中的文本框获取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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