6

在 XAML 中:

<ResourceDictionary>
    <Color x:Key="BrushColor1">Red</Color>
    <Color x:Key="BrushColor2">Black</Color>

    <LinearGradientBrush x:Key="GradientBrush1" StartPoint="0,0.5" EndPoint="1,0.5">
        <GradientStop Color="{DynamicResource BrushColor2}" Offset="0" />
        <GradientStop Color="{DynamicResource BrushColor1}" Offset="1" />
    </LinearGradientBrush>
</ResourceDictionary>

在 C# 中:

    public void CreateTestRect()
    {
        Rectangle exampleRectangle = new Rectangle();
        exampleRectangle.Width = 150;
        exampleRectangle.Height = 150;
        exampleRectangle.StrokeThickness = 4;
        exampleRectangle.Margin = new Thickness(350);

        ResourceDictionary resources = this.Resources;
        resources["BrushColor1"] = Colors.Pink;
        resources["BrushColor2"] = Colors.RoyalBlue;
        Brush brush =(Brush)this.FindResource("GradientBrush1");

        exampleRectangle.Fill = brush;
        canvas.Children.Insert(0, exampleRectangle);
    }

如何在 C# 的运行时更改这些颜色元素。LinearGradientBrush 应该动态更改吗?

我想做这样的事情:

(Color)(this.FindResource("BrushColor1")) = Colors.Pink;

但我失败了。

4

2 回答 2

6

您可以直接覆盖资源字典中的值。

例如:

ResourceDictionary resources = this.Resources; // If in a Window/UserControl/etc
resources["BrushColor1"] = System.Windows.Media.Colors.Black;

话虽如此,我通常建议不要这样做。相反,我将有两组颜色,每组都有自己的键,并使用某种机制来切换在运行时将哪种颜色分配给您的值。这使您可以将整个逻辑留在 xaml 本身中。

于 2012-11-15T18:14:23.607 回答
3

我刚刚解决了。看起来只有LinearGradientBrush不支持DynamicResource的颜色。即使你覆盖了动态颜色,LinearGradientBrush本身也不会更新。PS:SolidColorBrush支持运行时颜色变化。改为执行以下操作:

LinearGradientBrush linearGradientBrush = (LinearGradientBrush)(this.FindResource("GradientBrush1"));
linearGradientBrush.GradientStops[0].Color = color1;
linearGradientBrush.GradientStops[1].Color = color2;

如果LinearGradientBrush隐藏在 Resource Dictionary 中定义的嵌套复杂画笔中,则使LinearGradientBrush出现,并为其分配一个键。

于 2012-11-16T16:47:19.137 回答