tags:

views:

176

answers:

3

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>
'<'/Rectangle>

When I click a button on my screen I want to change the "black" gradientstop to "red". Any suggestions

A: 

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

    }
Weston Goodwin
+1  A: 

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.

Michael S. Scherotter
A: 

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.

Weston Goodwin