Drop Shadow / Glow Effect using XAML

Jeffrey Smith / Tuesday, April 5, 2011
As most of know Silverlight has built in effects, however these effects can be pretty memory intensive. One solution would be is to use an image for the shadow, however if you’re planning for the object casting the shadow or glow to dynamically scale the image will either pixelate or not scale. The other solution is to create your drop shadows using rectangles in XAML.
Here I illustrate the memory usage of a drop shadow effect, a drop shadow built in XAML, and no drop shadow at all on a Dialog Window in Silverlight.
No Drop Shadow
Drop Shadow using Silverlight’s built in Effects
A drop Shadow using XAML
We can see that no drop shadow is the winner in terms of performance but a drop shadow built with XAML is a very close second using only an extra 12kb. The Built in effect in Silverlight uses over 3,000 kb more!

So how do you create a drop shadow effect in XAML? It’s actually very easy. Just create an offset grid with negative margins (this will be the distance from you object the drop shadow will cast) and add a series of Rectangles with varying corner radiuses, margins, and opacity.

<Grid Margin="-2,-2,-6,-6">
<Rectangle Stroke="Black" Margin="5" RadiusX="7" RadiusY="7" Opacity="0.3"/>
                <Rectangle Stroke="Black" Margin="4" RadiusX="8" RadiusY="8" Opacity="0.25"/>
                <Rectangle Stroke="Black" Margin="3" RadiusX="9" RadiusY="9" Opacity="0.2"/>
                <Rectangle Stroke="Black" Margin="2" RadiusX="10" RadiusY="10" Opacity="0.15"/>
                <Rectangle Stroke="Black" Margin="1" RadiusX="11" RadiusY="11" Opacity="0.1"/>
                <Rectangle Stroke="Black" Margin="0" RadiusX="12" RadiusY="12" Opacity="0.05"/>
</Grid>
Note that my radius on my rectangles starts at 7 to match the radius of window that’s casting the shadow.  Also that the radius increases the farther it is from the object. 

 

You may want to add this drop shadow grid to a content control or user control, that way you only have to create the XAML once and just apply the content control or user control where ever you want a shadow.