0

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 >.<.

  • Why don't you simply pass a MainWindow reference to the LoadWindow on creation, either as constructor parameter or as a property? – Clemens Jun 23 '22 at 03:58

1 Answers1

0

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;
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thank you so much! After like 40h working on threads and background workers I feel so stupid and happy that it was something so simple this time. Big thanks – Crestfallen Vulpes Jun 23 '22 at 14:36