Search code examples
c#wpfvariableswindow

Pass variable from window to page


I would like to pass variable which I insert into textbox in Window to Page in WPF application I only found how could I do it other way.

Basically I need app to prompt for password which I need to use in different page.

I call window from page like this:

Password_Prompt PassWindow = new Password_Prompt();
PassWindow.Show();

It's just window with a textbox and a button and after I input a password and click ok, I would like to send the password into variable on page from I called the window.


Solution

  • The most efficient way to achieve this would be to raise an event when you click the button on the window and subscribe to it from the page.

    Window

    public event EventHandler<string> PasswordInput;
    
    // the function you are going to call when you want to raise the event
    private void NotifyPasswordInput(string password)
    {
        PasswordInput?.Invoke(this, password);
    }
    
    // button click event handler
    private void OnButtonClick(object sender, RoutedEventArgs e)
    {
        // get the password from the TextBox
        string password = myTextBox.Text;
    
        // raise the event
        NotifyPasswordInput(password);
    }
    

    Page

    ...
    Password_Prompt PassWindow = new Password_Prompt();
    
    // add this part to subscribe to the event
    PassWindow.PasswordInput += OnPasswordInput;
    
    PassWindow.Show();
    ...
    
    // and the method to handle the event
    private void OnPasswordInput(object sender, string password)
    {
        // use the password from here
    }