wpf之渐变色LinearGradientBrush
xmal代码:
1 <Grid Name="grid1"> 2 <Grid.Background> 3 <LinearGradientBrush> 4 <LinearGradientBrush.GradientStops> 5 <GradientStop Offset="0" Color="red"></GradientStop> 6 <GradientStop Offset="0.5" Color="blue"></GradientStop> 7 <GradientStop Offset="1" Color="Yellow"></GradientStop> 8 </LinearGradientBrush.GradientStops> 9 </LinearGradientBrush> 10 </Grid.Background> 11 </Grid>
也可以用C#代码实现,等价的C#代码为:
1 public MainWindow() 2 { 3 InitializeComponent(); 4 MyLinearGradientBrush(); 5 } 6 7 public void MyLinearGradientBrush() 8 { 9 LinearGradientBrush brush = new LinearGradientBrush(); 10 11 GradientStop gs1 = new GradientStop(); 12 gs1.Offset = 0; 13 gs1.Color = Colors.Red; 14 brush.GradientStops.Add(gs1); 15 16 GradientStop gs2 = new GradientStop(); 17 gs2.Offset = 0.5; 18 gs2.Color = Colors.Blue; 19 brush.GradientStops.Add(gs2); 20 21 GradientStop gs3 = new GradientStop(); 22 gs3.Offset = 1; 23 gs3.Color = Colors.Yellow;
//因为GradientStops属性返回一个GradientStopCollection对象,而且GradientStopCollection类实现了IList接口 24 brush.GradientStops.Add(gs3);//所以这句代码的本质是IList list = brush.GradientStops; list.Add(gs3); 25 26 grid1.Background = brush; 27 }