0

Please can someone tell me the technique that would be used, for the following scenario.

I would like to authenticate users, before I allow my code to perform another action.

I have a method that opens a new window that contains my authentication form (username and password).

    private bool userLogin()
    {
        Window loginInterface = new Window()
        {
            Title = "Please Login",
            Content = new login(),
            Height = 282,
            Width = 300,
            ResizeMode = ResizeMode.NoResize,
            WindowStartupLocation = WindowStartupLocation.CenterOwner

        };

        loginInterface.Owner = this;

        loginInterface.ShowDialog();

        return true;

    }

I'm calling this method like so, on button click:

    private void perform_action(object sender, RoutedEventArgs e)
    {
        if (!userLogin())
        {
            // Failed login, do nothing
        }
        else
        {
            // Authentication successful, perform action
            delete_item();
        }
    }

The window opens fine, but how can I now make my method return true or false based on the what the user does on the opened form?

So when the user clicks the login button named login_button, my code already validates the credentials, but I need the 'bool' value sent back.

Can I make my first window almost wait for an action to be performed on another window and get the response back?

3 Answers 3

1

The Window.ShowDialog() method actually already returns a bool?. This can be set at any point from within the Window by setting (for example) this.DialogResult = true. You can then close the window and access the value from the calling code.

To close the window with a result:

this.DialogResult = true;

...and then to use that result in the calling code:

var myWindow = /*create window*/;
var result = myWindow.ShowDialog();
if (result == true)
{
     //...
}
2
  • 1. Close is not necessary 2. result is nullable, so that statement won't work like this
    – H.B.
    Nov 1, 2011 at 17:22
  • Thank you for this! I was having trouble at first because I had the Window set as a UserControl. Once I changed that, I was able to access the DialogResult variable.
    – Luke
    Nov 2, 2011 at 10:05
0

To close the login screen you can set DialogResult to true or false, and ShowDialog returns this value. For other things you can create events on the second window and subscribe to them on the first.

0

userLogin should return something other than true.

I would do something like this (based on the code shown):

return loginInterface.WasSuccessful;  // you'd have to add this property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.