views:

149

answers:

2

I've been using the same bit of code for several versions of my app with no problems, but I'm now mysteriously receiving NullRerefenceExceptions with the following:

this.Loaded += delegate {
    deleteBrush = new DeleteBrushAdorner( background );
    AdornerLayer al = AdornerLayer.GetAdornerLayer( background );
    al.Add( deleteBrush ); // null ref here??
};

background is just a Border element.

My two thoughts on what could be causing it are a) switching to .NET 4.0, and b) placing instances of the above element (which is a UserControl) in an ItemsControl.

Oddly this doesn't happen all the time, and it's hard to predict when it will happen, so it's not reliable.

+2  A: 

The docs for AdornerLayer.GetAdornerLayer specify:

If no adorner layers are found, the method returns null.

So my guess is that there are no adorner layers... do you have any reason to believe that this shouldn't be the case? What guarantee are you currently relying on that there will be an adorner layer in the visual tree?

Jon Skeet
The same thing occurs if I use an `AdornerDecorator` instead of a `Border`, although I now see according to MSDN it "Provides an adorner layer for elements *beneath* it in the visual tree." Let me try wrapping the Border in an AdornerLayer...
chaiguy
So far so good, actually. Sorry for the dumb question :$
chaiguy
A: 

I'm curious as to whether or not this was really solved. An AdornerDecorator provides an AdornerLayer for element below it -- and everything will be below it. It is a decorator, meaning it has a Child that is the content. That content is being provided with an AdornerLayer. So, if you put an AdornerDecorator in your XAML and the child is the border, the border does have an AdornerLayer.

Furthermore, Window defines an AdornerDecorator as the top of the visual tree so any element in a Window will have an AdornerLayer above it. So, if your conent above was in a Window...

Tony Brummel
The solution that ended up working was to just put an `AdornerDecorator` *above* (i.e. as a parent of) the `Border` in the visual tree. It was indeed in a window, albeit a chromeless one, but perhaps this is an issue with .NET 4 because it worked fine without having the `AdornerDecorator` in .NET 3.5.
chaiguy