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

cro*_*mup 10 c# wpf textbox user-input

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

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

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

private void Button_Click(object sender, RoutedEventArgs e)
{
    var h = text1.Text;
}
Run Code Online (Sandbox Code Playgroud)

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

duD*_*uDE 17

就像@Michael McMullin已经说过的那样,你需要在函数之外定义变量,如下所示:

string str;

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

// somewhere ...
DoSomething(str);
Run Code Online (Sandbox Code Playgroud)

关键是:变量的可见性取决于其范围.请看一下这个解释.


bre*_*per 7

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

<TextBox Height="251" ... Name="Content" />
Run Code Online (Sandbox Code Playgroud)

在代码中:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string content = Content.Text;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

好吧,这是一个如何使用MVVM执行此操作的简单示例.

首先编写一个视图模型:

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

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

    public event PropertyChangedEventHandler PropertyChanged;
}
Run Code Online (Sandbox Code Playgroud)

然后编写转换器,这样就可以将字符串转换为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");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样编写你的XAML代码:

<Window x:Class="StackoverflowHelpWPF5.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>
Run Code Online (Sandbox Code Playgroud)

  • 哇,这是一个很平常的代码.人们想知道为什么我讨厌MVVM/MVC ....但是很棒的演示. (3认同)