如何在运行时更改资源字典中的颜色

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;

但是我失败了。
2个回答

6
您可以直接在资源字典中覆盖值。
例如:
ResourceDictionary resources = this.Resources; // If in a Window/UserControl/etc
resources["BrushColor1"] = System.Windows.Media.Colors.Black;

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


我尝试过了,但是我仍然无法在画布上改变颜色。不管怎样,谢谢你。 - dongx
@XiaoruiDong 这样做不行 - 你需要找到实际存储它的资源字典来进行更改。 - Reed Copsey
1
我刚刚解决了它。看起来只有LinearGradientBrush不支持DynamicResource。其余的画刷,如SolidColorBrush都支持它。 - dongx

3
我刚刚解决了这个问题。看起来只有LinearGradientBrush不支持使用DynamicResource来改变颜色。即使您覆盖动态颜色,LinearGradientBrush本身也不会更新。PS:SolidColorBrush支持运行时颜色更改。请按照以下步骤操作:
LinearGradientBrush linearGradientBrush = (LinearGradientBrush)(this.FindResource("GradientBrush1"));
linearGradientBrush.GradientStops[0].Color = color1;
linearGradientBrush.GradientStops[1].Color = color2;

如果LinearGradientBrush被隐藏在资源字典中定义的嵌套复杂画笔中,您可以让LinearGradientBrush浮现出来,并为其分配一个键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接