When can I dispose an IDisposable WPF control e.g. WindowsFormsHost?

后端 未结 4 1106
情书的邮戳
情书的邮戳 2021-01-02 01:38

The WPF control WindowsFormsHost inherits from IDisposable.

If I have a complex WPF visual tree containing some of the above controls what event or method can I use

4条回答
  •  萌比男神i
    2021-01-02 01:46

    Building from Todd's answer I came up with this generic solution for any WPF control that is hosted by a Window and want's to guarantee disposal when that window is closed.

    (Obviously if you can avoid inheriting from IDisposable do, but sometimes you just can't)

    Dispose is called when the the first parent window in the hierarchy is closed.

    (Possible improvement - change the event handling to use the weak pattern)

    public partial class MyCustomControl : IDisposable
        {
    
            public MyCustomControl() {
                InitializeComponent();
    
                Loaded += delegate(object sender, RoutedEventArgs e) {
                    System.Windows.Window parent_window = Window.GetWindow(this);
                    if (parent_window != null) {
                        parent_window.Closed += delegate(object sender2, EventArgs e2) {
                            Dispose();
                        };
                    }
                };
    
                ...
    
            }
    
            ...
        }
    

提交回复
热议问题