c#Wp8:获取文本框输入值时出错?

时间:2013-09-03 09:06:04

标签: c# windows-phone-8

它说createPasswordrepeatPassword不在当前上下文中。为什么会发生什么?

代码;

public MainPage()
    {
        InitializeComponent();
        TextBox createPassword = new TextBox();
        createPassword.Width = 400;
        TextBox repeatPassword = new TextBox();
        repeatPassword.Width = 400;
        Button createButton = new Button();
        createButton.Content = "Create New Password";
        createButton.Click += new RoutedEventHandler(savePassword);
        StackPanel content = new StackPanel();
        content.HorizontalAlignment = HorizontalAlignment.Center;
        content.Children.Add(createPassword);
        content.Children.Add(repeatPassword);
        content.Children.Add(createButton);
        LayoutRoot.Children.Add(content);
        }
        void savePassword(object sender, RoutedEventArgs e)
        {
            string password1 = createPassword.Text;
            string password2 = repeatPassword.Text;
        }

1 个答案:

答案 0 :(得分:1)

createPasswordrepeatPassword必须是类成员才能在不同的类方法中使用它们:

TextBox createPassword;
TextBox repeatPassword;

public MainPage()
{
    InitializeComponent();
    createPassword = new TextBox();
    createPassword.Width = 400;
    repeatPassword = new TextBox();
    repeatPassword.Width = 400;
    Button createButton = new Button();
    createButton.Content = "Create New Password";
    createButton.Click += new RoutedEventHandler(savePassword);
    StackPanel content = new StackPanel();
    content.HorizontalAlignment = HorizontalAlignment.Center;
    content.Children.Add(createPassword);
    content.Children.Add(repeatPassword);
    content.Children.Add(createButton);
    LayoutRoot.Children.Add(content);
}
void savePassword(object sender, RoutedEventArgs e)
{
    string password1 = createPassword.Text;
    string password2 = repeatPassword.Text;
}