您可以从 App.Xaml.cs 调用 MainWindow.Xaml.cs 中的函数吗?
这似乎是可行的,但由于某种原因,我没有想到正确的方法。我是 C# 和 .NET 的新手,所以我希望这不是一个荒谬的问题:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不知道你为什么要这样做。这似乎不是最好的设计,但在不知道你正在做什么的细节的情况下,我无法对此发表评论。以下是完成此操作的方法:
在 App.Xaml.cs 中:
请注意,您必须在启动后执行此操作。如果您想在启动之前执行此操作,则需要创建
MainWindow
对象并将其分配给this.MainWindow
: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:
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 tothis.MainWindow
:很高兴看到有人开始!坚持下去,您会发现该语言非常强大,最终您将看到他们希望您在编码中使用的设计方法。
我只能解释您可能想做这样的事情的几种情况。
1)调用一些独立于窗口的函数:
如果您的代码不依赖于或引用您的MainWindow,也许您应该将其移出MainWindow的代码文件并将其放在其他地方?您可以拥有任意数量的 .cs 文件,因此请花点时间整理内容。你会很高兴你以后这么做了。
2) 加载后,在窗口上执行一些初始化任务:
在窗口代码中,在构造函数中的 InitializeComponent() 调用之后插入代码。 (这是没有返回类型的方法,它只是“public MainWindow() {”
请记住,当您需要传递某些内容时,可以向构造函数添加参数。默认的无参数构造函数没有什么神奇之处, Visual Studio 创建。您可以通过这种方式避免创建大量复杂的代码。通常,在窗口代码中进行初始化比加载窗口更好,
3) 从窗口中获取一些简单数据
您是否了解了如何操作。创建自定义属性了吗?这真的很容易。
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.