从 WPF 应用程序的文本框中获取用户输入

Get user input from a textbox in a WPF application

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

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

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

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

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

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

string str;

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

// somewhere ...
DoSomething(str);

重点是:变量的可见性取决于它的作用域。请看this explanation.

// WPF

// Data
int number;

// Button click event
private void Button_Click(object sender, RoutedEventArgs e) {
    // Try to parse number
    bool isNumber = int.TryParse(text1.Text, out number);
}

好吧,这是一个简单的例子,说明如何使用 MVVM 执行此操作。

首先写一个视图模型:

public class SimpleViewModel : INotifyPropertyChanged
{
    private int myValue = 0;

    public int MyValue
    {
        get
        {
            return this.myValue;
        }
        set
        {
            this.myValue = value;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

然后编写一个转换器,这样您就可以将字符串转换为 int,反之亦然:

[ValueConversion( typeof(int), typeof(string))]
class SimpleConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int returnedValue;

        if (int.TryParse((string)value, out returnedValue))
        {
            return returnedValue;
        }

        throw new Exception("The text is not a number");
    }
}

然后像这样编写 XAML 代码:

<Window x:Class="WhosebugHelpWPF5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:[YOURNAMESPACEHERE]"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:SimpleViewModel></local:SimpleViewModel>
    </Window.DataContext>
    <Window.Resources>
        <local:SimpleConverter x:Key="myConverter"></local:SimpleConverter>
    </Window.Resources>
    <Grid>
        <TextBox Text="{Binding MyValue, Converter={StaticResource myConverter}, UpdateSourceTrigger=PropertyChanged}"></TextBox>
    </Grid>
</Window>

您也可以只为您的控件命名:

<TextBox Height="251" ... Name="Content" />

在代码中:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string content = Content.Text;
}