在 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;
但我失败了。