更改资源字典中的SolidColorBrush#颜色失败:属性是只读的

时间:2016-07-01 19:43:09

标签: c# wpf xaml resourcedictionary

我在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));

我有什么遗失的东西吗?

1 个答案:

答案 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用于更改。在哪里改变 - 这是开发人员的愿望。

相关问题