You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 10:00:00