0

I have a problem.

I would like to call my method in xaml (mainWindow) in LinearGradientBrush --> GradientStop

So I would like to change color in background for an animation. I have a function which has several parameters as :

public static List<Color> GetGradientColors(Color start, Color end, int steps)
{
    return GetGradientColors(start, end, steps, 0, steps - 1);
}

public static List<Color> GetGradientColors(Color start, Color end, int steps, int firstStep, int lastStep)
{
    var colorList = new List<Color>();
    if (steps <= 0 || firstStep < 0 || lastStep > steps - 1)
        return colorList;

    double aStep = (end.A - start.A) / steps;
    double rStep = (end.R - start.R) / steps;
    double gStep = (end.G - start.G) / steps;
    double bStep = (end.B - start.B) / steps;

    for (int i = firstStep; i < lastStep; i++)
    {
        byte a = (byte)(start.A + (int)(aStep * i));
        byte r = (byte)(start.R + (int)(rStep * i));
        byte g = (byte)(start.G + (int)(gStep * i));
        byte b = (byte)(start.B + (int)(bStep * i));
        colorList.Add(Color.FromArgb(a, r, g, b));
    }

    return colorList;
}

In code XAML :

<LinearGradientBrush StartPoint="0.0, 0.6" EndPoint="1.0, 0.6">
    <GradientStop Color="{ Binding GetGradientColors(green, yellow, 2)}" Offset="0"/>
</LinearGradientBrush>

Is it possible to do this?

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Why are you trying to do that? The gradient brush interpolates on its own, you just need one stop for `Green` and one for `Yellow`. – H.B. Jul 10 '14 at 15:27

2 Answers2

0

First declare a property of type ObservableCollection<Color>, lets say named Colours:

public ObservableCollection<Color> Colours { get; set; }

Then set the property in your constructor:

Colours = GetGradientColors(Colors.Green, Colors.Yellow, 2);

Then data bind to it in XAML:

It's not exactly what you wanted, but it's about as close as you're going to get.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
0

You could implement a converter that can be used in the binding and pass all the arguments needed as Binding.ConverterParameter.

Alternatively, as this does not require a "binding" anyway, you could implement a markup extension, that takes the arguments as constructor parameters:

<GradientStop Color="{me:GradientColor Green, Yellow, 2}" Offset="0"/>
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Please Would you tell me how to call your GetGradientColors() function in GradientStop ? I can't call this. And thanks for reply. – DeveloperTech2013 Jul 10 '14 at 16:33
  • @DeveloperTech2013: Read the documentation i linked to for the respective methods, should contain all the info you need. – H.B. Jul 10 '14 at 17:01