在资源字典中更改 SolidColorBrush#Color 失败:属性是只读的 [英] Changing SolidColorBrush#Color in resource dictionary failed: Property is readonly

查看:88
本文介绍了在资源字典中更改 SolidColorBrush#Color 失败:属性是只读的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 App.xaml 中有一个 SolidColorBrush 资源,如下所示:

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

有什么我遗漏的吗?

推荐答案

如果您想在 App.xaml 中为您的 SolidColorBrush 动态设置颜色,那么您不应设置颜色的值:

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>

并且在您的控件中,您应该通过 DynamicResource 进行绑定:

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>

然后要更改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 用于更改.在哪里更改 - 这是开发人员的愿望.

DynamicResources are used for changing. Where to change - this is the wish of the developer.

这篇关于在资源字典中更改 SolidColorBrush#Color 失败:属性是只读的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆