Reputation: 55
i have one function that will update my UI
public void Checking()
{
// Do Something
}
I want to call these function Upon opening the program : Which i believe i should call it in main:
public MainWindow()
{
InitializeComponent();
Checking();
}
But here the I'm getting an error:
Exception has been thrown by the target of an invocation.
P.S: im using WPF... Any solution for this?
Upvotes: 0
Views: 121
Reputation: 568
In your constructor setup the Windows Loaded event and call your Checking() method from there. The UI is not ready for interaction in the contructor, not until the XAML has been completely loaded. WPF has an event to let you know this has happened (the Loaded event).
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Checking();
}
If you still get errors then you will need to look at your inner exception, you should be told what is causing the error. You could also step through the Checking() method to see what line the error happens on.
[edit] Here are some additional resources on the Loaded event and the order of events in a WPF page lifecycle:
MSDN: FrameworkElement.Loaded Event Control Lifecycle
Upvotes: 1
Reputation: 32481
Same thing happens to me.
In WPF when Exception
occurs in the constructor of the form this message is thrown. so try calling the Checking()
function in the FormLoad
event handler of the MainForm
. This way you will see what kind of Exception
you have in your program.
Upvotes: 0
Reputation: 1124
You can use the function the way you are using. But something inside the Checking() might need your Panel (or something) to be loaded.
You can create an event handler that is fired once your panel gets loaded. And then you can call your checking() function from there.
<StackPanel Loaded="myStackPanelLoaded" />
Upvotes: 0