【问题标题】:Changing SolidColorBrush#Color in resource dictionary failed: Property is readonly [duplicate]在资源字典中更改 SolidColorBrush#Color 失败:属性是只读的 [重复]
【发布时间】:2016-07-01 19:43:09
【问题描述】:

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

我有什么遗漏的吗?

【问题讨论】:

  • 这是预期的行为。您应该交换资源,而不是属性。是在同一个字典中交换资源字典或其他资源。那里有很多关于动态主题的精彩文章,人们花了很多时间在上面进行更详细的解释。

标签: c# wpf xaml resourcedictionary


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多