Trong XAML:Làm thế nào để thay đổi tài nguyên từ điển Màu sắc trong thời gian chạy
<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>
Trong 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);
}
Làm thế nào để thay đổi những yếu tố màu trong thời gian chạy trong C#. LinearGradientBrush sẽ được thay đổi động?
Tôi muốn làm một cái gì đó như thế này:
(Color)(this.FindResource("BrushColor1")) = Colors.Pink;
nhưng tôi đã thất bại.
Tôi đã thử, nhưng tôi vẫn không thể thay đổi màu trên canvas của mình. Dù sao, cảm ơn u. – dongx
@XiaoruiDong Điều đó sẽ không hoạt động - bạn cần tìm từ điển tài nguyên thực tế để lưu trữ nó để thay đổi nó. –
Tôi vừa giải quyết nó. Có vẻ như chỉ ** LinearGradientBrush ** không hỗ trợ ** DynamicResource **. Phần còn lại như ** SolidColorBrush ** hỗ trợ nó. – dongx