How to use disposable view models in WPF?

后端 未结 2 1454
南旧
南旧 2021-02-07 21:15

How do I ensure view models are properly disposed of if they reference unmanaged resources or have event handlers such as handling elapsed on a dispatcher timer. In the first c

2条回答
  •  死守一世寂寞
    2021-02-07 22:15

    One possible, although not perfect solution:

    Implement IDisposable on the View Model, then use this extension method in the constructor of the view.

        public static void HandleDisposableViewModel(this FrameworkElement Element)
        {
            Action Dispose = () =>
                {
                    var DataContext = Element.DataContext as IDisposable;
                    if (DataContext != null)
                    {
                        DataContext.Dispose();
                    }
                };
            Element.Unloaded += (s, ea) => Dispose();
            Element.Dispatcher.ShutdownStarted += (s, ea) => Dispose();
        }
    

提交回复
热议问题