简体   繁体   中英

What Generates This Error 'Exception has been thrown by the target of an invocation'?

I am developing a Windows Phone 8 APP and I have created a popup element on Page Launch and use as a static variable popup.

private void Application_Launching(object sender, LaunchingEventArgs e)
{
     RemoveCurrentDeactivationSettings();

     APPCommon.popupsetup();
}

//APPCOMMON Page
public static Popup busyindicator;
public static void popupsetup()
{
    busyindicator = new Popup()
    {
        Child = new Border()
        {
            Child = new Telerik.Windows.Controls.RadBusyIndicator()
            {
                FontSize = 25,
                IsRunning = true,
                IsEnabled = true,
                Content = "Processing...",
                Foreground = new SolidColorBrush(Colors.White)
            },
            Opacity = 0.8,
            Name = "busyindicate",
            Background = new SolidColorBrush(Colors.Black),
            Width = Application.Current.Host.Content.ActualWidth,
            Height = Application.Current.Host.Content.ActualHeight
        }
    };
}

It works fine most of the time even when it is in heavy modes too. However, I get an error on rare occasion when the app enters IDLE Mode (Lock Screen or Start Menu) when I get back to the app from start menu instead of using Back Key I get an error saying ' Exception has been thrown by the target of an invocation ' on the following line which is in my DefaultPage .

Exception In Detail ' Element is already the child of another element. '

public MainPage()
{
     InitializeComponent();
     App.RootFrame.RemoveBackEntry();
     this.LayoutRoot.Children.Add(APPCommon.busyindicator); // Error Occurs
}

Therefore, I would like to know why this is happening and what I Should do to solve this.

I would suggest using a "factory" method instead of a shared instance of the Popup. To use a global static UI element is begging for trouble ...

public static Popup CreatePopup()
{
    return new Popup
    {
        // ...
    };
}

And:

public MainPage()
{
     InitializeComponent();
     this.LayoutRoot.Children.Add(APPCommon.CreatePopup());
}

try this:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    App.RootFrame.RemoveBackEntry();
    this.LayoutRoot.Children.Add(APPCommon.busyindicator);
}

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