How to get user input from a popup control

徘徊边缘 提交于 2019-12-11 23:04:42

问题


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
}

回答1:


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



来源:https://stackoverflow.com/questions/17794943/how-to-get-user-input-from-a-popup-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!