簡體   English   中英

從 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);

重點是:變量的可見性取決於它的作用域。 請看一下這個解釋

好吧,這是一個如何使用 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="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>

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

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

在代碼中:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string content = Content.Text;
}
// 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM