WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?


Note: If your WPF UserControl is hosted in MFC Window, you may want to clean-up the ViewModel that is DataContext of your UserControl.

Since Unloaded event is not called reliably for the UserControl when the hosting MFC Window closes, there is a need for another solution.

XAML:
<UserControl x:Class="Views.MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
            
    </Grid>
</UserControl>

Code Behind:
using System;
using ViewModels;
 
namespace Views
{
    public partial class MyUserControl
    {
        public MyUserControl()
        {
            DataContext = new MyUserControlViewModel();
            InitializeComponent();
            Dispatcher.ShutdownStarted += OnDispatcherShutDownStarted;
        }
 
        private void OnDispatcherShutDownStarted(object sender, EventArgs e)
        {
            var disposable = DataContext as IDisposable;
            if (!ReferenceEquals(null, disposable))
            {
                disposable.Dispose();
            }
        }
    }
}

ViewModel:
using System;
 
namespace ViewModels
{
    public class MyUserControlViewModel : IDisposable
    {
        public void Dispose()
        {
            // Cleanup code
            // SettingsRepository.Save();
            // WebServiceConnection.Close();
            // etc.
        }
    }
}

Comments

Post a Comment

Popular posts from this blog

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?