Xamarin.ios Xamarin表单-iOS自定义呈现程序-处理观察者

Xamarin.ios Xamarin表单-iOS自定义呈现程序-处理观察者,xamarin.ios,xamarin.forms,Xamarin.ios,Xamarin.forms,当自定义的ListView页面内容被取消时,以下崩溃。错误表明我的观察者没有被处理掉 public class ChatListViewRenderer : ListViewRenderer { private IDisposable _onContentSizeChangedObserver; private IDisposable _onFrameChangedObserver; protected override void OnElementChanged(El

当自定义的
ListView
页面内容被取消时,以下崩溃。错误表明我的观察者没有被处理掉

public class ChatListViewRenderer : ListViewRenderer
{
    private IDisposable _onContentSizeChangedObserver;
    private IDisposable _onFrameChangedObserver;

    protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
    {
        base.OnElementChanged(e);
        if (Control == null) return;

         _onContentSizeChangedObserver = Control.AddObserver(new NSString("contentSize"), NSKeyValueObservingOptions.OldNew, OnContentSizeChanged);
        _onFrameChangedObserver = Control.AddObserver(new NSString("frame"), NSKeyValueObservingOptions.OldNew, OnFrameChanged);
    }


    protected override void Dispose(bool disposing)
    {
        _onContentSizeChangedObserver.Dispose();
        _onFrameChangedObserver.Dispose();
        base.Dispose(disposing);
    }
}

OnElementChanged被调用两次——创建控件时调用,然后在释放时调用

if(e.NewElement != null)
      addobserver and do other stuff
if(e.oldElement!=null)
       remove observer and destroy everything you allocated
一个更“直观”的例子:

应用方向变更服务器上的私有IDisposable; 受保护的覆盖无效OnElementChanged(ElementChangedEventArgs e) { 碱基。一个元素改变(e); if(e.OldElement!=null) { _onAppOrientationChangedObserver?.Dispose(); } if(例如NewElement!=null) { if(控件!=null) { _OnApp-OrientationChangeDobServer=NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationIDChangeNotification,(obj)=> { _uiOrientation=UIApplication.SharedApplication.StatusBarOrientation; _deviceOrientation=UIDevice.CurrentDevice.Orientation; }); } } }
if(e.NewElement != null)
      addobserver and do other stuff
if(e.oldElement!=null)
       remove observer and destroy everything you allocated
private IDisposable _onAppOrientationChangedObserver;

protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
   base.OnElementChanged (e);

   if (e.OldElement != null)
   {
      _onAppOrientationChangedObserver?.Dispose();
   }

   if (e.NewElement != null) 
   {
      if (Control!=null)
      {
            _onAppOrientationChangedObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification, (obj) =>
            {
              _uiOrientation = UIApplication.SharedApplication.StatusBarOrientation;
              _deviceOrientation = UIDevice.CurrentDevice.Orientation;
            });
      }
   }

}