I’m using Silverlight to draw some shapes and text on top of an image. The shapes use a common set of gradient colors so I have a predefined set of GradientStopCollections that I intended to use to define the brushes used to fill the shapes. This works as long as I only use each of the GradientStopCollections up to one time. If I try to instantiate a LinearGradientBrush using one of the GradientStopCollections a second time, it throws an ArgumentException stating “Value does not fall within the expected range.”
_yellowFill = new GradientStopCollection();
_yellowFill.Add(new GradientStop(){ Color = Color.FromArgb(128, 255, 255, 0), Offset = 0 });
_yellowFill.Add(new GradientStop() { Color = Color.FromArgb(128, 128, 128, 0), Offset = 1 });
…
_shapeLinearFillBrush = new LinearGradientBrush(_yellowFill, 90);
...
_shapeLinearFillBrush = new LinearGradientBrush(_yellowFill, 90);
The last line above will throw the exception. Why is it throwing this exception and how can I use my GradientStopCollections to define multiple gradient brushes?
I believe that the issue has to do with Silverlight lacking freezable objects. If you are using WPF, this should not be an issue. There is no way in Silverlight to reuse the same GradientStopCollection. I don’t think that you can even use the same GradientStop. To work around this you can create an extension method on that clones the GradientStopCollection like so: