c# - 更改资源字典中的 SolidColorBrush#Color 失败 : Property is readonly

标签 c# wpf xaml resourcedictionary

我有一个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/

相关文章:

c# - 异步方法的延迟进度报告

c# - 使用基于 Entity Framework 一对多属性的 ObservableCollection

c# - uwp : how to change background color of listview item based on its value?

wpf - WPF 星号是做什么的(宽度 ="100*")

c# - EF 核心中的 NOT LIKE(表达式树)

c# - 通过代码将自定义链接添加到 SharePoint 列表设置页面

c# - 使用 ObjectSet 有什么好处

wpf - WPF设计时间数据困惑

c# - 为什么我的 WPF TabControl 会自动切换选项卡?

c# - 点击 ListView 项目上的手势