Object disposing in Xamarin.Forms

前端 未结 3 1275
庸人自扰
庸人自扰 2021-01-17 12:56

I\'m looking for the right way to dispose objects in a Xamarin Forms application. Currently i\'m using XAML and MVVM coding style. Then from my view model i get a reference

3条回答
  •  情书的邮戳
    2021-01-17 13:53

    I have View Models that conform to IDisposable. So I needed a way for the Page's BindingContext to be disposed when the page is no longer needed.

    I used the suggestion of Nick which uses OnParentSet being set to NULL to known when the page is no longer needed.

    The SafeContentPage class can be used in place of ContentPage. Iff The binding context supports IDisposable will it automatically try to dispose the binding context.

    public class SafeContentPage : ContentPage
    {
        protected override void OnParentSet()
        {
            base.OnParentSet();
            if (Parent == null)
                DisposeBindingContext();
        }
    
        protected void DisposeBindingContext()
        {
            if (BindingContext is IDisposable disposableBindingContext) {
                disposableBindingContext.Dispose();
                BindingContext = null;
            }
        }
    
        ~SafeContentPage()
        {
            DisposeBindingContext();
        }
    }
    

    The OnDisappearing method isn't a reliable technique as there are platform differences in terms of when it is called, and just because the page disappeared doesn't mean its View Model is no longer needed.

提交回复
热议问题