0

它说createPassword并且repeatPassword不在当前上下文中。为什么以及会发生什么?

代码;

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;
        }
4

1 回答 1

1

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

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;
}
于 2013-09-04T05:32:07.933 回答