简体   繁体   中英

Unable to retrieve input from user via MessageDialog before the code moving forward

I am trying to invoke a MessageDialog that will prompt for user input, and then proceed with that input.

Below is the code for that.

XAML

<Button Content="Click" Click="Button_Click"/>

XAML.CS

public MainPage()
{
    this.InitializeComponent();
}
private int _res;
private void Button_Click(object sender, RoutedEventArgs e)
{
    Click_Helper(sender, e);
    System.Diagnostics.Debug.WriteLine(_res.ToString());
    //Some other work will be done here
}

private async Task Click_Helper(object sender, RoutedEventArgs e)
{
    MessageDialog msgbox = new MessageDialog("Hello there");

    msgbox.Commands.Clear();
    msgbox.Commands.Add(new UICommand { Label = "Yes", Id = 0 });
    msgbox.Commands.Add(new UICommand { Label = "No", Id = 1 });

    var result = await msgbox.ShowAsync();
    _res = (int)result.Id;
}

In the above code, I want the _res to be set Before the Debug Writeline, but somehow I can't achieve that. Unfortunately for UWP, it seems the MessageDialog doesn't have any option for me to use it synchronously.

I have been trying to use .Wait() method for the Task but it causes deadlock (I read somewhere about this and it had something to do with UI thread being locking itself from showing the MessageDialog) I also tried several other methods but none works. I am starting to think this is not possible.

Please help shed some lights on this.

In the above code, I want the _res to be set Before the Debug Writeline,

Please add the await keyword before Click_Helper method.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await Click_Helper(sender, e);
    System.Diagnostics.Debug.WriteLine(_res.ToString());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM