如何在运行时更改SolidColorBrush资源的颜色

如何在运行时更改SolidColorBrush资源的颜色

本文介绍了如何在运行时更改SolidColorBrush资源的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时更改在另一个资源字典中使用的资源字典中的颜色?

How can I change a colour in a resource dictionary being used in another resource dictionary at runtime?

这是我的设置:

Colours.xaml:

<SolidColorBrush x:Key="themeColour" Color="#16A8EC"/>

Styles.xaml:

<Style x:Key="titleBar" TargetType="Grid">
    <Setter Property="Background" Value="{DynamicResource themeColour}"/>
</Style>

Window.xaml

.....
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="res/Styles.xaml"/>
    <ResourceDictionary Source="res/Colours.xaml"/>
</ResourceDictionary.MergedDictionaries>
.....

<Grid Style="{DynamicResource titleBar}"></Grid>

背后的代码:

Application.Current.Resources["themeColour"] = new SolidColorBrush(newColour);

代码运行时,网格的颜色不变.我不认为Application.Current.Resources ["themeColour"]指的是我的solidcolorbrush资源,就好像我在尝试为其分配新颜色之前尝试访问它时,却得到了一个空对象引用异常.

When the code runs the colour of the grid doesn't change. I don't think Application.Current.Resources["themeColour"] is referring to my solidcolorbrush resource as when if I try to access it before assigning it a new colour, I get a null object reference exception.

那么,我应该如何访问资源"themeColour"?

So, how should I access the resource "themeColour"?

推荐答案

为使您的代码正常工作, ResourceDictionary 必须位于文件 App.xaml 中,其中 ResourceDictionary 应该是:

In order to your code to work, ResourceDictionary must be in a file App.xaml where ResourceDictionary should be:

App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary/StyleDictionary.xaml"/>
            <ResourceDictionary Source="Dictionary/ColorDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

隐藏代码

private void Window_ContentRendered(object sender, EventArgs e)
{
    SolidColorBrush MyBrush = Brushes.Black;

    Application.Current.Resources["themeColour"] = MyBrush;
}

为什么最好使用App.xaml

  • 正确存储在此文件中的所有样式和资源字典,因为它是专门为此创建的-所有应用程序资源都可以从一个地方获得.它还可以很好地影响应用程序的性能.

  • correctly all styles and resource dictionaries stored in this file because it was created specifically for this - to all application resources were available from one place. It can also affect application performance in a good way.

在某些情况下,已经成功使用了 StaticResource ,但没有成功使用 DynamicResource (资源放置在Window.Resources中).但是,在将资源移至 App.xaml 中之后,一切开始正常工作.

there have been cases where a StaticResource has been used successfully, but not DynamicResource (resources are placed in the Window.Resources). But after moving the resource in App.xaml, everything started to work.

这篇关于如何在运行时更改SolidColorBrush资源的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:29