0

I have this class that allows only one instance per window stolen from other stackoverflow question:

public static class WindowManager
    {
        public static T GetWindow<T>()
        {
            var t = Application.Current.Windows.OfType<T>().FirstOrDefault();
            if (t == null)
            {
                t = (T)Activator.CreateInstance(typeof(T));
            }
            return t;
        }

        public static T CreateOrFocusWindow<T>()
        {
            var t = GetWindow<T>();
            if (t is Window)
            {
                var window = t as Window;
                if (window.Visibility != Visibility.Visible)
                    window.Show();
                if (window.WindowState == WindowState.Minimized)
                    window.WindowState = WindowState.Normal;
                window.Focus();
            }
            return t;
        }
    }

And now I want to open new window:

private async void Button_OnClick(object sender, RoutedEventArgs e)
        {
            LoadingOn(); //enables progress ring etc
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    WindowManager.CreateOrFocusWindow<Window1>();
                });
            });
            LoadingOff(); //disables progress ring etc
        }

But the problem is that UI is locked anyway (constructor of window contains long operation). I don't have any ideas how to bypass it.

There might be a way to simply first create instance of the window, and then call long operation not from constructor, but from OnLoading event, but its completely different approach that requires adding loading spinner to every new window. I just want to open new window when data is ready without nuking the way my code currently works. It looks like its impossible, but I'm not master of C# and WPF yet.

  • Please do not ask the same question again. You do already know that you have to move the long running code out of the Window constructor. You haven't told us anything about what exactly you are doing there, so the question can't be answered. You may perhaps consider exposing a static async Create method in your Window class that first asynchronously prepares the state of a new Window, and than creates that Window by means of a Dispatcher.Invoke call. – Clemens Aug 03 '21 at 13:11
  • I exactly said what I want to achieve. It might be impossible, but I won't know until someone answers. Very well, I will ask again in 90 minutes. –  Aug 03 '21 at 13:17
  • That won't get you very far here, I'm afraid. Better rephrase the question with details about your specific code. See [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Clemens Aug 03 '21 at 13:19

0 Answers0