【问题标题】:How to call my method in mainWindow for linearGradientBrush?如何在 mainWindow 中为 linearGradientBrush 调用我的方法?
【发布时间】:2014-07-10 14:49:32
【问题描述】:

我有问题。

我想在 LinearGradientBrush 的 xaml (mainWindow) 中调用我的方法 --> GradientStop

所以我想改变动画的背景颜色。我有一个函数,它有几个参数:

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

在代码 XAML 中:

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

可以这样做吗?

【问题讨论】:

  • 你为什么要这么做?渐变画笔会自行插值,您只需为Green 停一停,为Yellow 停一停。

标签: c# wpf xaml lineargradientbrush


【解决方案1】:

首先声明一个ObservableCollection&lt;Color&gt;类型的属性,假设命名为Colours

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

然后在你的构造函数中设置属性:

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

然后在 XAML 中将数据绑定到它:

这不是您想要的,但它与您将得到的差不多。

【讨论】:

    【解决方案2】:

    您可以实现一个converter,可以使用in the binding 并将所有需要的参数作为Binding.ConverterParameter 传递。

    另外,由于这无论如何都不需要“绑定”,您可以实现一个markup extension,它将参数作为构造函数参数:

    <GradientStop Color="{me:GradientColor Green, Yellow, 2}" Offset="0"/>
    

    【讨论】:

    • 请问您能告诉我如何在 GradientStop 中调用您的 GetGradientColors() 函数吗?我不能这样称呼。并感谢您的回复。
    • @DeveloperTech2013:阅读我链接到的相应方法的文档,应该包含您需要的所有信息。
    猜你喜欢
    • 2014-10-18
    • 2015-05-14
    • 1970-01-01
    • 2015-05-21
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多