Can you call a function in MainWindow.Xaml.cs from App.Xaml.cs?

nicky picture nicky · Apr 7, 2011 · Viewed 12.5k times · Source

This seems doable but for some reason the proper way is not occurring to me. I am new to C# and .NET so I hope this isn't a ridiculous question :)

Answer

Josh G picture Josh G · Apr 7, 2011

Not sure why you would want to do this. It doesn't seem like the best design, but without knowing the details of what you are doing, I can't comment about that. Here's how this could be done:

In App.Xaml.cs:

var main = App.Current.MainWindow as MainWindow; // If not a static method, this.MainWindow would work
main.MyFunction();

Note that you would have to do this AFTER startup. If you want to do it BEFORE startup, you'll need to create the MainWindow object and assign it to this.MainWindow:

var window = new MainWindow();
this.MainWindow = window;

window.Show();

window.MyFunction();