通过代码访问我们在Silverlight中定义的资源是很简单的,我们首先定义如下一个资源

1 <UserControl x:Class="EightBall.Page"
2 xmlns="http://schemas.microsoft.com/client/2007"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 Width="400" Height="300">
5 <UserControl.Resources>
6 <LinearGradientBrush x:Key="BackgroundBrush">
7 <LinearGradientBrush.GradientStops>
8 <GradientStop Offset="0.00" Color="Yellow" />
9 <GradientStop Offset="0.50" Color="White" />
10 <GradientStop Offset="1.00" Color="Purple" />
11 </LinearGradientBrush.GradientStops>
12 </LinearGradientBrush>
13 </UserControl.Resources>
14

15 </UserControl>
我们在UserControl的Resources属性中定义了一个LinearGradientBrush类型的资源,并将它的索引定义为"BackgroundBrush",接下来通过下面这段代码就可以访问此资源了

Code
LinearGradientBrush brush = (LinearGradientBrush)this.Resources["BackgroundBrush"];
Color color = brush.GradientStops[0].Color;
brush.GradientStops[0].Color = brush.GradientStops[2].Color;
brush.GradientStops[2].Color = color;
需要注意的是由于Silverlight仅支持静态资源,所以不能将以定义好的资源替换为其他对象,例如下面这段代码所示:

Code
SolidColorBrush brush = new SolidColorBrush(Colors.Yellow);
this.Resources["BackgroundBrush"] = brush;