GetAdornerLayer returns null

I have a problem with

AdornerLayer AdornerLayer = AdornerLayer.GetAdornerLayer (layout);

This method always returns null.

What am I doing wrong?

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Layout layout = new Layout(); layout.Background = Brushes.White; layout.ClipToBounds = true; layout.SnapsToDevicePixels = true; layout.Width = 4965; layout.Height = 3515; AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(layout); adornerLayer.Add(new LayoutAdorner(layout)); } } public class Layout : Canvas { public Visual GetVisualChildAtPoint(Point point) { return VisualTreeHelper.HitTest(this, point).VisualHit as Visual; } } public class LayoutAdorner : Adorner { public LayoutAdorner(UIElement adornedElement) : base(adornedElement) { } protected override void OnRender(DrawingContext drawingContext) { } } 
+4
source share
3 answers

AdornerLayer for the window will not be created until the window is loaded and a handle is created.

Instead of putting this in the constructor, you may need to delay and add an advertiser when the window loads.

+6
source

After the form is updated, call Content.UpdateLayout (); Ensures that all visual child Content elements for the layout are correctly updated. Official MSDN

(I'm not so smart, I just copied the solution from here): AdornerLayer.GetAdornerLayer () returns NULL for all controls in the panel

0
source

(An old question, but I ran into this problem and could not find a solution) AdornerLayer.GetAdornerLayer is looking for AdornerLayer in the visual tree up.

In the constructor, the visual tree is not composed. You need to put your code in the Window.Loaded event.

Another problem:

Layout layout = new Layout(); ... AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(layout);

Search up. But the "layout" is the top one (without a parent). Then GetAdornerLayer returns null.

To get the Window AdornerLayer, you need to take the composer on Windows (and not on Window, because Window is the top one). My solution is called the first composer in XAML "root":

AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this.root);

edit:

This method can return an adorner layer from some types of WPF element:

 //If no adorner layer is found, return null private static AdornerLayer GetAdornerLayer(Visual visual) { var decorator = visual as AdornerDecorator; if (decorator != null) return decorator.AdornerLayer; var presenter = visual as ScrollContentPresenter; if (presenter != null) return presenter.AdornerLayer; var visualContent = (visual as Window)?.Content as Visual; return AdornerLayer.GetAdornerLayer(visualContent ?? visual); } 
0
source

All Articles