繁体   English   中英

从WPF中的页面内调用公共MainWindow函数

[英]Call a public MainWindow function from within a Page in WPF

我有一个WPF应用程序,它有一个主窗口和几个我导航到的页面,如下所示:

例如,从一页到另一页,我使用:

NavigationService.Navigate(new MyPage1());

从我的主窗口显示我使用的页面:

_mainFrame.Navigate(new PageHome());

我在MainWindow上有一个公共函数,我想从内页调用。

我该怎么做呢??

您不应该直接调用该方法。

您应该做的是在您的页面中引发一个事件并让MainWindow订阅该事件。 然后,该事件处理程序可以调用相关方法。

在PageHome:

public event EventHandler SomethingHappened;
private void MakeSomethingHappen(EventArgs e){
    if(SomethingHappened != null){
        SomethingHappened(this, e);
    }
}

在MainWindow:

pageHome.SomethingHappened += new EventHandler(pageHome_SomethingHappened);

void pageHome_SomethingHappened(object sender, EventArgs e){
     MyMethod();
}

还有一种使用Registry的技术,这将是从其他类调用其他类的一个类的完美方法(在多个项目中分割的类所需)。

  1. 使公共函数成为接口的一部分

     interface ISomeInterface { void RequierdMethod();} public partial class RequiedImplementer: Window, ISomeInterface { void RequiredMethod() { } } 
  2. Registry.RegisterInstance<ISomeInterface >(new RequiedImplementer()); //Initialize all interfaces and their corresponding in a common class.

  3. 在下面的应用程序中的任何地方调用apt函数

     Registry.GetService<ISomeInterface>().RequiredMethod(); 

这里注册类是自定义创建的,它只保存实例并在必要时返回。 接口应该被所有类引用。 当您需要多个项目的互操作时,此解决方案更有效。

以下解决方案让我从另一个页面调用MainWindow函数;

((MainWindow)System.Windows.Application.Current.MainWindow).FunctionName(params);

虽然我更喜欢使用事件和代理的技术,但我展示了另一种解决方案。

var mainWnd = Application.Current.MainWindow as MainWindow;
if(mainWnd != null)
   mainWnd.Navigate(new MyPage1());

暂无
暂无

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

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