I have the following elements in UI:
- One main window
- Two secondary windows
I want to be able to open the 3rd window from my second window. I already have 2 buttons on my 1st Main window that opens the 2nd and 3rd window, but I also want to add a button to my 2nd window that opens the 3rd one.
In my MainWindow.xaml.cs I have these 2 functions that I added and they work fine
private void BtnClickP_L(object sender, RoutedEventArgs e)
{
Main.Content = new Patient_list();
}
private void BtnClickP_I(object sender, RoutedEventArgs e)
{
Main.Content = new Patient_info();
}
But when I try to do the same in my Patient_list.xaml.cs file, I got an error when I try to say:
private void BtnClickM_i(object sender, RoutedEventArgs e) { MainWindow.Content = new Patient_info(); // error here CS0103 Main does not exists in current context }
Also if I try to add it to my main file (MainWindow.xaml.cs) just like this:
private void BtnClickP_L(object sender, RoutedEventArgs e)
{
Main.Content = new Patient_list();
}
private void BtnClickP_I(object sender, RoutedEventArgs e)
{
Main.Content = new Patient_info();
}
private void BtnClickM_i(object sender, RoutedEventArgs e)
{
Main.Content = new Patient_info();
}
I have no error, I can run the program, but when clicking on it, it does nothing.
CodePudding user response:
You need to create a MainWindow object first, Try to access your MainWindow like this in your Patient_list.cs:
private void BtnClickM_i(object sender, RoutedEventArgs e)
{
MainWindow MW = (MainWindow)Application.Current.MainWindow;
MW.Content = new Patient_info();
}
CodePudding user response:
Get a reference to the MainWindow
and set the Content
of its Main
element:
var window = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
window?.Main.Content = new Patient_info();