Actually I m trying to close my window by firing the event from my ViewModel
. Everything works fine and awesome, but I know that I must unsbscribe my event to avoid memory leaks. thus I implement the IDisposable
interface and I unsbscribe the event inside the Dispose
method.
Below is my code :
public partial class MainWindow : Window, IDisposable
{
private MainViewModel viewModel;
public MainWindow()
{
InitializeComponent();
DataContext = viewModel = new MainViewModel();
this.viewModel.RequestClose += CloseWindow;
}
void CloseWindow(object sender, EventArgs e)
{
this.Close();
}
public void Dispose()
{
////here we need to unsubscribe the event
this.viewModel.RequestClose -= this.CloseWindow;
}
}
What I need to know :
- Is that code correct
- When the
GC
will be called and excute the dispose method - Is there a better way to do such a thing