简体   繁体   English

你能从App.Xaml.cs中调用MainWindow.Xaml.cs中的函数吗?

[英]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 :) 我是C#和.NET的新手,所以我希望这不是一个荒谬的问题:)

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: 在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 : 如果要在启动之前执行此操作,则需要创建MainWindow对象并将其分配给this.MainWindow

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

window.Show();

window.MyFunction();

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: 1)调用一些独立于窗口的函数:

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? 如果您的代码不依赖于或引用您的MainWindow,也许您应该将其移出MainWindow的代码文件并将其放在其他地方? You can have as many .cs files as you want, so take your time and organize things. 你可以拥有任意数量的.cs文件,所以要花时间整理一下。 You'll be glad you did later. 你以后会很高兴。

2) Performing some initialization task on the window, after it loads: 2)加载后在窗口上执行一些初始化任务:

In your window's code, insert your code after the InitializeComponent() call in the constructor. 在窗口的代码中,在构造函数中的InitializeComponent()调用之后插入代码。 (This is the method that doesn't have a return type, it's just "public MainWindow() {" (这是没有返回类型的方法,它只是“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. 请记住,当您需要传入某些内容时,可以向构造函数添加参数。对于Visual Studio创建的默认无参数构造函数,没有什么不可思议的。 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 3)在窗口内外获取一些简单数据

Have you learned how to create custom properties yet? 您是否学会了如何创建自定义属性? It's really easy. 这真的很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM