Search code examples
windows-phone-7user-inputmessagebox

How to get user input from a popup control


I have a UserControl that utilizes a popup window in wp7. The user control has a text box for input, and a submit button. My issue is that the code does not halt once the popup is shown. It continues on through the code and does not wait for the user to press submit.

What is a good practice for making the code "halt" similar to a message box with an "Okay" button?

//my custom popup control
InputBox.Show("New Highscore!", "Enter your name!", "Submit");
string name = InputBox.GetInput();
//it does not wait for the user to input any data at this point, and continues to the next piece of code

if (name != "")
{
     //some code
}

Solution

  • You could accomplish this with either an event, or an async method. For the event you would subscribe to a Closed event of your popup.

        InputBox.Closed += OnInputClosed;
        InputBox.Show("New Highscore!", "Enter your name!", "Submit");
    
    ...
    
    private void OnInputClosed(object sender, EventArgs e)
    {
        string name = InputBox.Name;
    }
    

    You would fire the event when the user pushes the OK button

    private void OnOkayButtonClick(object sender, RoutedEventArgs routedEventArgs)
    {
        Closed(this, EventArgs.Empty);
    }
    

    The other option is to use an async method. For this you need the async Nuget pack. To make a method async you use two main objects, a Task and a TaskCompletionSource.

    private Task<string> Show(string one, string two, string three)
    {
        var completion = new TaskCompletionSource<string>();
    
        OkButton.Click += (s, e) =>
            {
                completion.SetResult(NameTextBox.Text);
            };
    
    
        return completion.Task;
    }
    

    You would then await the call to the show method.

    string user = await InputBox.Show("New Highscore!", "Enter your name!", "Submit");
    

    I believe the Coding4Fun toolkit also has some nice input boxes