I have a ViewModel that on receiving an event from a Model, shows a dialog to the user by newing up the dialog's ViewModel and passing it to the dialog for data binding, i.e.,
public class MainViewModel
{
...
private void OnModelRaisedEvent(object sender, EventArgs e)
{
DialogViewModel dialogViewModel = new DialogViewModel();
Window dialog = new DialogView(dialogViewModel);
dialog.ShowDialog();
}
}
In the dialog's view I hook into a button click to close the window, i.e.,
public class DialogView : Window
{
public DialogView(DialogViewModel viewModel)
{
InitializeComponent();
Loaded += (s,e) => {DataContext = viewModel; };
}
...
private void ButtonOnClick(object sender, RoutedEventArgs e)
{
Close();
}
}
Since only the DialogView is using the DialogViewModel, can I be confident that I won't get a memory leak here?
For example, if I open and close the dialog multiple times, will the DialogViewModel get GC'd when the DialogView is closed so not to accumulate multiple instances of the DialogViewModel. Watched memory usage in task manager, and it does go up when opening and closing DialogView multiple times, but not sure if this is because the GC just hasn't kicked in.
Actually you do have dependency injection right now, since you are injecting the viewmodel into the dialog via constructor.
While the dialog view is running, it contains a reference to dialogViewModel in MainViewModel.
When you close the dialog, the control is given back to the OnModelRaisedEvent method, and immediately after that, the method finishes (no other code after dialog.ShowDialog()) and GC collects the variable dialogViewModel, since its scope is restricted to that method.
So, the bottom line is: you should be able use your code without problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With