There is a parent window that is the basis of the program, and there are several sub windows under it. Editor is one of the sub window and I'm making it. The code is as follows:
// This is Code-Behind
public partial class MyEditor : Window
{
private static readonly Lazy<MyEditor> lazy = new Lazy<MyEditor>(() => new MyEditor());
public static MyEditor Instance { get => lazy.Value; }
public EditorViewModel EditorViewModel { get; } = new EditorViewModel();
private MyEditor()
{
InitializeComponent();
DataContext = this;
Application.Current.MainWindow.Closing += MainWindow_Closing;
}
public void Show()
{
Visibility = Visibility.Visible;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
e.Cancel = true;
Visibility = Visibility.Hidden;
}
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
Application.Current.Shutdown();
}
}
Since there should only be one Editor, I made it to a singleton class using the Lazy class. And I used the Visibility property to reuse the Window. Lastly, by registering an event handler to the Closing event of Application.Current.MainWindow, MyEditor can be exit immediately through the Shutdown() method.
MyEditor class is not implemented with MVVM. View, ViewModel, and Model were created separately, and MyEditor class refers to these and uses them.
Now MyEditor works as I want but, I wonder if this approach is the right way. Or is there a problem I'm not aware of?