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?
The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.
Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.
Here's how to create a TextBox in XAML and in code. TextBox textBox = new TextBox(); textBox. Width = 500; textBox. Header = "Notes"; textBox.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With