(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); }
Orwel source share