Reputation: 4747
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??
Upvotes: 6
Views: 12507
Reputation: 89
The following solution worked for me to call a MainWindow function from another page;
((MainWindow)System.Windows.Application.Current.MainWindow).FunctionName(params);
Upvotes: 6
Reputation: 357
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).
Make the public functions to be part of an Interface
interface ISomeInterface { void RequierdMethod();}
public partial class RequiedImplementer: Window, ISomeInterface
{
void RequiredMethod() { }
}
Registry.RegisterInstance<ISomeInterface >(new RequiedImplementer()); //Initialize all interfaces and their corresponding in a common class.
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.
Upvotes: 2
Reputation: 2487
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());
Upvotes: -2
Reputation: 928
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();
}
Upvotes: 8