Home > Back-end >  Change Visibility of Main Window from a different window
Change Visibility of Main Window from a different window

Time:06-24

Sorry for the stupid question but I can't get it to work.

I got a MainWindow that opens another window.

public static Window2 LoadWindow = new Window2();

        public MainWindow()
        {
            InitializeComponent();
            LoadWindow.Show();

Later in the code, I Start a function that creates a Background worker in the new window

if (MainWindow.Start == true)
            {
                MainWindow.LoadWindow.LoadImage(null, null);
                MainWindow.Start = false;
            }
        public void LoadImage(object sender, RoutedEventArgs e)
        {

            worker = new BackgroundWorker();
        ...

And then I tried this to Change the Visibility of the MainWindow.

        private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(new Action(() => {
                Application.Current.MainWindow.Visibility = Visibility.Visible;
            }));
            

        }

I thought Application.Current.MainWindow would point to my MainWindow but the debugger said that Window2 is the Current.MainWindow.

Actually, I am completely confused about the MainWindow. Typically I initialize a class with a name and use it with that name. (e.g. Window2=class, LoadWindow=it's name) But what is the name of the MainWindow or how can I interact with it from another window. It's so confusing when the MainWindow != the MainWindow >.<.

CodePudding user response:

You could either inject LoadWindow with a reference to the MainWindow when you create it in the constructor, or you could get a reference to the MainWindow using the Application.Current.Windows collection:

var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
if (mainWindow != null)
    mainWindow.Visibility = Visibility.Visible;
  • Related