简体   繁体   中英

Call a public MainWindow function from within a Page in WPF

I have a WPF Application that has a main window and several pages that I navigate to like so:

eg From one page to another I use:

NavigationService.Navigate(new MyPage1());

And from my main window to show a page I use:

_mainFrame.Navigate(new PageHome());

I have a public function on my MainWindow that I want to call from a within page.

How do I do this??

You shouldn't call the method directly.

What you should do is raise an event in your page and have the MainWindow subscribe to the event. That event handler can then call the method in question.

In PageHome:

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

In MainWindow:

pageHome.SomethingHappened += new EventHandler(pageHome_SomethingHappened);

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

Also there is one more technique using Registry this will be the perfect way to call a fucntion of one class from other from other class(required for classes split in multiple projects).

  1. Make the public functions to be part of an Interface

     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. Call the apt functions anywhere in ur application like below

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

Here register class is custom created which just holds the instance and returns whenever neccessary. Interfaces should be referenced by all classes. This solution is more valid when you want interop by multiple projects.

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

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

Although I would prefer the technique with events and delegates, I show another solution.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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