开发者

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 adorne开发者_JAVA技巧r 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.


It all depends on where you are calling the code and where the control resides. In the case you've provided, the control hasn't yet been instantiated via the InitializeComponent() method. You'll actually have to place the control somewhere in one of your views or just have it declared in XAML ahead of time to be able to pull the AdornerLayer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜