简体   繁体   中英

Show MessageDialog from app.xaml.cs in Windows Store app

Im trying to show a message to the user when connection to the internet is lost

I have this method on my App.xaml.cs

static async void NetworkInformation_NetworkStatusChanged(object sender)
    {

        //Get the Internet connection profile
        //ConnectionProfile connectionProfileInfo = null;
        try
        {
            ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

            if (InternetConnectionProfile == null)
            {
                ApplicationData.Current.LocalSettings.Values["INTERNET"] = false;

                ShowBox("Internet Lost");

                Frame rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(LoginPage));
            }
            else
            {
                ApplicationData.Current.LocalSettings.Values["INTERNET"] = true;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unexpected exception occurred: " + ex.ToString());
        }

    }

and this other one

public async static void ShowBox(string msg)
    {
        try
        {

            await new MessageDialog(msg, "No Internet").ShowAsync();
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
        }
    }

When i cause a connection lost ( disable my internet connection ) the ShowBox method gets called, and i get this exception on it:

Invalid window handle.

This API must be called from a thread with a CoreWindow or a window must have been set explicitly.

Is there any way to show a MessageDialog from that event?

在此处输入图片说明 Try to add this:

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    MessageDialog msg= new MessageDialog("No Internet");
    msg.ShowAsync();
 });

Manuel Patrone answer is almost correct. just small fix for his answer.

await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async() =>
{
    MessageDialog msg= new MessageDialog("No Internet");
    await msg.ShowAsync();
 });

If you're running through the Desktop Bridge ensure that you're initializing your store context properly. See Using the StoreContext class with the Desktop Bridge for more information about it.

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