I've been using the same bit of code for several versions of my app with no problems, but I'm now mysteriously receiving NullRerefenceException
s 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.
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?