PDFTron Xamarin Forms监听AnnotationModified事件时CurentPdfViewCtrlFragment为空问询
DocumentView2监听AnnotationModified事件实现方案
正确监听时机说明
CurrentPdfViewCtrlFragment 仅在DocumentView2完成初始化、PDF文档加载流程执行完毕后才会完成实例化,过早访问就会出现空值,你需要绑定DocumentView2的DocumentLoaded事件作为入口注册监听,该事件触发时所有关联控制器都已完成初始化。
具体实现步骤
- 在页面的
OnAppearing生命周期或者DocumentView2实例化完成的位置,先注册DocumentLoaded事件回调 - 在
DocumentLoaded回调中判空后再注册AnnotationModified事件,示例代码如下:
// 绑定文档加载完成事件 documentView2.DocumentLoaded += OnDocumentLoaded; private void OnDocumentLoaded(object sender, EventArgs e) { var pdfFragment = documentView2.CurrentPdfViewCtrlFragment; if (pdfFragment?.PdfViewCtrl == null) return; // 注册注解修改监听 pdfFragment.PdfViewCtrl.AnnotationModified += OnAnnotationModified; } private void OnAnnotationModified(object sender, PDFViewCtrl.AnnotationModifiedEventArgs e) { // 此处编写注解修改后的业务逻辑 var annotation = e.Annot; int pageNumber = e.PageNum; }
- 补充注意:页面销毁或者文档关闭前要记得解绑事件,避免内存泄漏,可以在
OnDisappearing或者DocumentClosing事件回调中执行解绑操作:
private void OnDocumentClosing(object sender, EventArgs e) { var pdfFragment = documentView2.CurrentPdfViewCtrlFragment; if (pdfFragment?.PdfViewCtrl != null) { pdfFragment.PdfViewCtrl.AnnotationModified -= OnAnnotationModified; } documentView2.DocumentLoaded -= OnDocumentLoaded; }
内容的提问来源于stack exchange,提问作者Balaji Gunasekaran
相关产品推荐
相关产品推荐

