从 WPF 中的一个代码隐藏中调用另一个代码隐藏中的方法

发布于 2024-12-02 16:45:16 字数 313 浏览 5 评论 0原文

从另一个窗口的代码隐藏调用窗口代码隐藏中的方法的最佳方法是什么?例如,我的 MainWindow 后面的代码中有一个方法 ShowSamples(),我有一个单独的窗口 Window2,一旦用户单击Window2 上的按钮 我希望执行 MainWindow 后面代码中的 ShowSamples() 方法。我将如何实现这一目标?

注意:窗口之间没有相互引用,它们不是从给定的类继承,也没有父子关系,1 个应用程序中有 2 个完全独立的窗口。

What is the best way of calling a method that is in the code behind of a window from the code behind of another window? For example I have a method ShowSamples() in the code behind of my MainWindow, I have a separate window Window2, once the user clicks a Button on Window2 I want the ShowSamples() method in the code behind of MainWindow to be executed. How would I go about achieving this?

NOTE: The windows do not have a reference to each other, they do not inherit from a given class and do not have a parent-child relation ship, 2 completely separate windows in 1 application.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱ヾ落雨殇 2024-12-09 16:45:16

如果您尝试调用当前主窗口上的方法,您可以访问应用程序主窗口,并使用强制转换调用其方法。假设您的 MainWindow 称为 SamplesWindow,这应该可以工作:

((SamplesWindow)Application.Current.MainWindow).ShowSamples();

If your trying to call a method on your current MainWindow, you can access the applications main window, and call its method using a cast. Assuming your MainWindow is called SamplesWindow, this should work:

((SamplesWindow)Application.Current.MainWindow).ShowSamples();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文