{"record":{"id":"ab1eab2ac2b891cb","repo":"dotnet/wpf","slug":"sr-format-sr-nopresentationcontextforgivenelement","errorCode":null,"errorMessage":"SR.Format(SR.NoPresentationContextForGivenElement, annotatedElement)","messagePattern":"SR\\.Format\\(SR\\.NoPresentationContextForGivenElement, annotatedElement\\)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/Annotations/Component/AnnotationComponentManager.cs","lineNumber":177,"sourceCode":"            Debug.Assert(annotatedElement != null, \"the annotatedElement should inherit from UIElement\");\n\n            // if annotation component is already in presentation context, nothing else to do\n            if (component.PresentationContext != null) return;\n\n            // otherwise host in the appropriate adorner layer\n            AdornerLayer layer = AdornerLayer.GetAdornerLayer(annotatedElement); // note, GetAdornerLayer requires UIElement\n            if (layer == null)\n            {\n                if (PresentationSource.FromVisual(annotatedElement) == null)\n                {\n                    // The annotated element is no longer part of the application tree.\n                    // This probably means we are out of sync - trying to add an annotation\n                    // for an element that has already gone away.  Bug # 1580288 tracks\n                    // the need to figure this out.\n                    return;\n                }\n\n                throw new InvalidOperationException(SR.Format(SR.NoPresentationContextForGivenElement, annotatedElement));\n            }\n\n            // add to the attachedAnnotations\n            this.AddToAttachedAnnotations(attachedAnnotation, component);\n\n            // let the annotation component know about the attached annotation\n            // call add before adding to adorner layer so the component can be initialized\n            component.AddAttachedAnnotation(attachedAnnotation); // this might cause recursion in modify if annotation component adds to annotation\n\n            AdornerPresentationContext.HostComponent(layer, component, annotatedElement, reorder);\n        }\n\n        /// <summary>\n        /// Service indicates attached annotation has changed.\n        /// For now, take all annotation components maped from old attached annotation and map from new.\n        /// Then iterate through annotation components to let them know.\n        /// Note, this needs to change later.  If modify is radical, existing component might not want it anymore,\n        /// and new one might need to be found... ","sourceCodeStart":159,"sourceCodeEnd":195,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/Annotations/Component/AnnotationComponentManager.cs#L159-L195","documentation":"AnnotationComponentManager.AddComponent requires the annotated element to have an AdornerPresentationContext (obtained from its AdornerLayer) before an attached annotation's component can be added. When the element carries no presentation context — meaning it is not in a visual tree with a supported adorner layer — an InvalidOperationException naming the element is thrown.","triggerScenarios":"Calling AddAttachedAnnotation or ModifyAttachedAnnotation (via AnnotationService) for an element whose PresentationContext lookup returned null — e.g. the element is not loaded in a visual tree, or is hosted without an AdornerLayer/DocumentViewerBase.","commonSituations":"Attaching annotations to a FlowDocumentPageViewer/FlowDocumentReader content before it is loaded; annotating elements inside containers without an adorner layer; calls racing element unload (element removed from tree while annotations are applied); applying annotations after a viewer control was re-templated so the adorner layer is missing.","solutions":["Ensure the annotated element is fully loaded (handle Loaded event) and inside a DocumentViewerBase or a visual tree providing an AdornerLayer before attaching annotations.","Check AnnotationComponentManager/AdornerPresentationContext presence for the element before calling the API.","Defer annotation application until after layout; retry on Loaded if the element was mid-unload.","For custom hosting, add an AdornerDecorator so an adorner layer exists for the element."],"exampleFix":"// before\nservice.EnableAnnotations(); // element not loaded yet -> throws on attach\n// after\nelement.Loaded += (s, e) => service.EnableAnnotations(); // attach after element is in visual tree","handlingStrategy":"validation","validationCode":"bool hasContext = element != null && element.IsLoaded &&\n    AdornerLayer.GetAdornerLayer(element as Visual) != null;\nif (hasContext) service.AddAttachedAnnotation(attachedAnnotation);","typeGuard":"bool CanAttach(UIElement el) => el.IsLoaded && VisualTreeHelper.GetParent(el) != null && AdornerLayer.GetAdornerLayer(el) != null;","tryCatchPattern":"try { service.AddAttachedAnnotation(attachedAnnotation); }\ncatch (InvalidOperationException) { /* element lacks presentation context; defer to Loaded */ }","preventionTips":["Attach annotations only after the element is loaded into a viewer/adorner-layer tree","Use the Loaded event as the attach trigger","For custom hosts, ensure an AdornerDecorator exists","Re-apply annotations after viewer re-templating or tree rebuilds"],"tags":["wpf","annotations","missing-context","visual-tree"],"backgroundTag":"resource-not-found","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}