silverlight gradient
I was wondering if there is a way to programmatically change a stopgradient color specified in XAML. For example:
<Rectangle Width="1280" Height="1024">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="Black" Offset="0.0" />
<GradientStop Color="White" Offset="0.25" />
</LinearGradientBrush>
</Rectangle.Fill&g开发者_Go百科t;
</Rectangle>
When I click a button on my screen I want to change the "black" gradientstop to "red". Any suggestions
Add an x.Name attribute to the gradient stop in XAML. Then you can access it by name in the code behind.
<GradientStop Color="Black" Offset="0.0" x:Name="MyStop" />
then your code would be
MyStop.Color=Colors.Red;
You should also look at doing this with the Visual State Manager and a GoToState Action on the Click - then you could do this without any code. You shouldn't mix code with design - the design (color, gradient info) should be kept in XAML and use your code for logic.
I figured it out. Here is the code in C#:
Rectangle rect = new Rectangle();
GradientStop gs_black = new GradientStop();
GradientStop gs_white = new GradientStop();
LinearGradientBrush lgb = new LinearGradientBrush();
private void cb_test_Click(object sender, RoutedEventArgs e)
{
rect.Width = 1280;
rect.Height = 1024;
gs_black.Offset = 0;
gs_black.Color = Color.FromArgb(255, 0, 0, 0);
gs_white.Offset = .25;
gs_white.Color = Color.FromArgb(255, 255, 255, 255);
lgb.StartPoint = new Point(0, 0);
lgb.EndPoint = new Point(0, 1);
lgb.GradientStops = new GradientStopCollection();
lgb.GradientStops.Add(gs_black);
lgb.GradientStops.Add(gs_white);
rect.Fill = lgb;
canvasname.Children.Add(rect);
}
private void cb_change_color_Click(object sender, RoutedEventArgs e)
{
lgb.GradientStops.Remove(gs_black);
gs_black.Offset = 0;
gs_black.Color = Color.FromArgb(255, 0, 255, 0);
lgb.GradientStops.Add(gs_black);
}
Using '<'GradientStop Color="Black" Offset="0.0" x:Name="MyStop" /> worked. I searched for this topic online and a lot of people said it couldn't be done that way.
To change the color of GradientStop used in a resource you need to use the x:Key, for example
(this.Resources["xKeyName"] as LinearGradientBrush).GradientStops[0].Color = Color.FromArgb(255, 69, 69, 69);
This will set the color for the first GradientStop in the following UserControl resource
<UserControl.Resources>
<LinearGradientBrush x:Key="xKeyName">
<GradientStop Offset="0" /><!-- Colorset via code-behind -->
<GradientStop Color="Black" Offset="1.0" />
</LinearGradientBrush>
</UserControl.Resources>
精彩评论