Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Value From Window To Class WPF

Within a method in my class I call Login.Show(), which is a Login Window. I would like the window to pass the email back to the class when the Login button is clicked, without creating a new instance of the class.

Is there any way to do this?

Currently I have

Login loginWindow;
public void AppStartup {
    loginWindow = new Login();
    loginWindow.Show();
    //in this instance I'd like the email to be returned here

Within the Login.xaml.cs

public void Login_Click(object sender, RoutedEventArgs e)
{
    string email;
    try {
        email = InputEmail.Text;
        //ideally I would like to return email to AppStartup without
        //using new AppStartup(); , rather back in the same instance
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message); 
    }
}
like image 648
Explorex Avatar asked Sep 15 '25 09:09

Explorex


1 Answers

You could call ShowDialog() instead of Show() to display the window and then access the Text property of the InputEmail control directly:

loginWindow = new Login();
loginWindow.ShowDialog();
string email = loginWindow.InputEmail.Text;

Unlike Show(), ShowDialog() won't return until the window has been closed.

Or you could add a property to the Login window or its DataContext, and set this one when the button is clicked.

public string Email { get; set; }

public void Login_Click(object sender, RoutedEventArgs e)
{
    Email = InputEmail.Text;
}

string email = loginWindow.Email;
like image 142
mm8 Avatar answered Sep 17 '25 00:09

mm8