Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a WPF adorner layer first become available?

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!

like image 917
aoven Avatar asked Apr 16 '10 10:04

aoven


1 Answers

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.

like image 187
Abe Heidebrecht Avatar answered Sep 21 '22 18:09

Abe Heidebrecht