Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a public MainWindow function from within a Page in WPF

Tags:

c#

wpf

xaml

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

e.g 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??

like image 333
Harry Boy Avatar asked Dec 25 '22 16:12

Harry Boy


1 Answers

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();
}
like image 160
SnareHanger Avatar answered May 05 '23 04:05

SnareHanger