gayan1991
gayan1991

Reputation: 795

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.

Upvotes: 0

Views: 787

Answers (2)

McGarnagle
McGarnagle

Reputation: 102753

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());
}

Upvotes: 1

Amit Bhatiya
Amit Bhatiya

Reputation: 2621

try this:

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

Upvotes: 0

Related Questions