nicky
nicky

Reputation: 378

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

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 :)

Upvotes: 4

Views: 13899

Answers (2)

djdanlib
djdanlib

Reputation: 22476

Great to see someone starting out! Keep it up, you'll find the language to be powerful and eventually you will see the design methodologies they intend you to use with your coding.

I can only construe a few circumstances where you might want to do such a thing.

1) Calling some function that is independent of the window:

If your code doesn't depend on, or refer to, your MainWindow, maybe you should move it out of MainWindow's code file and put it somewhere else? You can have as many .cs files as you want, so take your time and organize things. You'll be glad you did later.

2) Performing some initialization task on the window, after it loads:

In your window's code, insert your code after the InitializeComponent() call in the constructor. (This is the method that doesn't have a return type, it's just "public MainWindow() {"

Remember that you can add parameters to your constructor, when you need to pass something in. There's nothing magical about the default parameterless constructor that Visual Studio creates. You might be able to avoid creating lots of convoluted code this way. It's generally better to do initialization in the window's code rather than loading the window,

3) Getting some simple data in or out of the window

Have you learned how to create custom properties yet? It's really easy.

Upvotes: 2

Josh G
Josh G

Reputation: 14256

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

Upvotes: 8

Related Questions