I'm trying to add an overlay effect to my UserControl and I know that's what adorners are used for in WPF. But I'm a bit confused about how they supposedly work. I figured that adorner layer is implicitly handled by WPF runtime, and as such, should always be available.
But when I create an instance of my UserControl in code, there is no adorner layer there. The following code fails with exception:
var view = new MyUserControl();
var target = view.GetAdornerTarget(); // This returns a specific UI control.
var layer = AdornerLayer.GetAdornerLayer(target);
if (layer == null)
{
throw new Exception("No adorner layer at the moment.");
}
Can someone please explain to me, how this is supposed to work? Do I need to place the UserControl instance into a top-level Window first? Or do I need to define the layer myself somehow? Digging through documentation got me nowhere.
Thank you!
The AdornerLayer
is generated by both the AdornerDecorator
and ScrollContentPresenter
classes. If there isn't either of these classes in the visual tree that parents your control, then it will not have an associated AdornerLayer
.
You could add an AdornerDecorator
to your UserControl
, but that will ensure that your Adorners
are only on top of controls that are descendants of the UserControl
.
The default ControlTemplate
for the Window includes an AdornerDecorator
, so if you add the UserControl
to a Window, then it should get the AdornerLayer
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With