2012-06-06 25 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

相關問題