我有一个SolidColorBrush
App.xaml 中的资源如下所示:
<SolidColorBrush Color="#73AF00" x:Key="BaseGreen"></SolidColorBrush>
我的所有样式(按钮、网格背景颜色等)都包含该资源,我希望当用户更改颜色设置时,整个应用程序颜色将更改为蓝色。
var color = System.Windows.Application.Current.Resources["BaseGreen"] as SolidColorBrush;
color.Color = Color.FromRgb(41, 128, 185);
I try what this answer suggest但是当我分配值时,抛出异常:
This property is set to read only and cannot be set
我也尝试过,但什么也没发生:
var color = this.TryFindResource("BaseGreen") as SolidColorBrush;
color = new SolidColorBrush(Color.FromRgb(41, 128, 185));
我有什么遗漏的吗?
最佳答案
如果您想在 App.xaml
中动态设置 SolidColorBrush
的颜色,那么您不应该设置颜色值:
<Application.Resources>
<SolidColorBrush x:Key="DynamicColor" />
</Application.Resources>
在您的控件中,您应该通过DynamicResource
进行绑定(bind):
<Label Name="MyLabel"
Content="Hello"
Background="{DynamicResource Color}" />
<Button Content="Change color"
Width="100"
Height="30"
Click="Button_Click" />
</Grid>
然后要更改资源
,您应该:
Application.Current.Resources["YourResource"] = YourNewValue;
让我举个例子:
private void Window_ContentRendered(object sender, EventArgs e)
{
SolidColorBrush YourBrush = Brushes.Green;
// Set the value
Application.Current.Resources["DynamicColor"] = YourBrush;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SolidColorBrush YourBrush = Brushes.Orange;
// Set the value
Application.Current.Resources["DynamicColor"] = YourBrush;
}
DynamicResources
用于更改。改哪里——这是开发者的意愿。
关于c# - 更改资源字典中的 SolidColorBrush#Color 失败 : Property is readonly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38152931/