2012-06-06 26 views
0

我使用Silverlight在图像顶部绘制了一些形状和文本。这些形状使用一组常用的渐变颜色,所以我有一组预定义的GradientStopCollections,我打算用它来定义用于填充形状的画笔。只要我一次只使用每个GradientStopCollections,这就可以工作。如果我第二次尝试使用其中一个GradientStopCollections实例化LinearGradientBrush,它会引发一个ArgumentException,指出“值不在预期范围内”。为什么重用GradientStopCollection会导致异常? (值不在预期的范围内)

 _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); 

上面最后一行将抛出异常。为什么抛出这个异常,我如何使用我的GradientStopCollections来定义多个渐变画笔?

+0

你试过引用集合作为一个静态资源,而不是(例如在App.xaml中)? –

+0

@HiTechMagic号我正在动态创建FrameworkElements以放置在画布中,所以我也在动态创建它们的画笔(因为我将稍后单独修改它们以响应事件)。如果我这样做会有什么区别? – xr280xr

+0

只是头脑风暴......有可能GradientStopCollection()只允许在一个父代中。我将需要深入研究GradientStopCollection的反汇编,以了解为什么并回馈给您。 –

回答

2

我认为这个问题与Silverlight缺乏可冻结对象有关。如果你使用的是WPF,这不应该是一个问题。 Silverlight无法重用相同的GradientStopCollection。我不认为你甚至可以使用相同的GradientStop。若要此你周围可以创建一个扩展方法对克隆像这样的GradientStopCollection:

_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 }); 

_shapeLinearFillBrush1 = new LinearGradientBrush(_yellowFill.Clone(), 90); 
_shapeLinearFillBrush2 = new LinearGradientBrush(_yellowFill.Clone(), 90); 

public static GradientStopCollection Clone(this GradientStopCollection stops) 
{ 
    var collection = new GradientStopCollection(); 

    foreach (var stop in stops) 
     collection.Add(new GradientStop() { Color = stop.Color, Offset = stop.Offset }); 

    return collection; 
} 
+0

谢谢@tjscience!我得出了同样的结论,并最终宣告了我的GradientStopCollections,或多或少地作为模板,并克隆它们,而不是直接使用它们。我仍然不明白为什么缺乏Freezable会导致异常。它如何知道GradientStopCollection已被使用,为什么它应该关心? – xr280xr

相关问题