Changing SolidColorBrush#Color in resource dictionary failed: Property is readonly [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 01:37:28

问题


I have a SolidColorBrush resource in the App.xaml like this:

<SolidColorBrush Color="#73AF00" x:Key="BaseGreen"></SolidColorBrush>

All my styles(buttons, grid backgroun color, etc, etc) contains that resource and i want that when the user change the color settings, the whole app color will be change to blue.

var color = System.Windows.Application.Current.Resources["BaseGreen"] as SolidColorBrush;
                color.Color = Color.FromRgb(41, 128, 185);

I try what this answer suggest but when I assign the value, an exception is throw:

This property is set to read only and cannot be set

I also try but nothing happended:

var color = this.TryFindResource("BaseGreen") as SolidColorBrush;
color = new SolidColorBrush(Color.FromRgb(41, 128, 185));

Is there something that I am missing?


回答1:


If you want dynamically set color for your SolidColorBrush in App.xaml, then you should not set the value of color:

<Application.Resources>
    <SolidColorBrush x:Key="DynamicColor" />
</Application.Resources>

And in your control you should bind through the DynamicResource:

    <Label Name="MyLabel" 
           Content="Hello" 
           Background="{DynamicResource Color}" />

    <Button Content="Change color"
            Width="100" 
            Height="30" 
            Click="Button_Click" />
</Grid>

Then to change Resource you should:

Application.Current.Resources["YourResource"] = YourNewValue;

Let me show an example:

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 are used for changing. Where to change - this is the wish of the developer.



来源:https://stackoverflow.com/questions/38152931/changing-solidcolorbrushcolor-in-resource-dictionary-failed-property-is-readon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!