我在App.xaml中有一个SolidColorBrush
资源,如下所示:
<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));
我有什么遗失的东西吗?
答案 0 :(得分:0)
如果您想为SolidColorBrush
中的App.xaml
动态设置颜色,那么不应设置颜色值:
<Application.Resources>
<SolidColorBrush x:Key="DynamicColor" />
</Application.Resources>
在您的控制中,您应该通过DynamicResource
:
<Label Name="MyLabel"
Content="Hello"
Background="{DynamicResource Color}" />
<Button Content="Change color"
Width="100"
Height="30"
Click="Button_Click" />
</Grid>
然后改变Resource
你应该:
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
用于更改。在哪里改变 - 这是开发人员的愿望。