I have this code stolen from somewhere else on this website:
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;
}
}
Its simple implementation of one instance of any window. But it creates certain issue.
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
await Task.Run(WindowManager.CreateOrFocusWindow<Window1>);
}
But it returns exception in line var t = Application.Current.Windows.OfType<T>().FirstOrDefault();
- System.InvalidOperationException - The calling thread cannot access this object because a different thread owns it.
I don't have any idea how to solve it without removing WindowManager
, but it simplifies code so much I really want to keep it.
Edit
This fixes exception, but UI is locked despite using async/await.
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
LoadingOn();
await Task.Run(() =>
{
Dispatcher.Invoke(() => //InvokeAsync changes nothing
{
WindowManager.CreateOrFocusWindow<FitnessWindow>();
});
});
LoadingOff();
}