在代码中设置静态资源 [英] Set static resource in code

查看:90
本文介绍了在代码中设置静态资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的App.xaml文件中有几种样式:

I have a few styles in my App.xaml file:

<SolidColorBrush x:Key="styleBlue" Color="#FF4B77BE"/>
<SolidColorBrush x:Key="styleRed" Color="#FFF64747"/>
<SolidColorBrush x:Key="styleOrange" Color="#FFF89406"/>
<SolidColorBrush x:Key="styleGreen" Color="#FF1BBC9B"/>
<SolidColorBrush x:Key="styleYellow" Color="#FFF9BF3B"/>

<Style x:Key="stackpanelBackground" TargetType="StackPanel">
    <Setter Property="Background" Value="{StaticResource styleBlue}"/>
</Style>

我想在我的mainpage.xaml.cs的代码中更改BackgroundProperty.

I want to change the BackgroundProperty in the code of my mainpage.xaml.cs.

我尝试使用这个:

Style style = Application.Current.Resources["stackpanelBackground"] as Style;          
style.Setters.SetValue(StackPanel.BackgroundProperty, "{StaticResource styleRed}");

但是我遇到了灾难性的失败例外.我认为这与{StaticResource styleRed}有关.有更好的方法吗?

But I get a catastrophic failure exception. I think it has to do with {StaticResource styleRed}. Is there a better way to do this?

推荐答案

A StaticResource 是静态的.一旦应用程序编译,您将无法更改它们.

A StaticResource is static. You can't change them once the application has compiled.

为此,有 DynamicResource :

DynamicResource 将在初始编译过程中创建一个临时表达式,从而将对资源的查找推迟到实际上需要所请求的资源值才能构造一个对象.

A DynamicResource will create a temporary expression during the initial compilation and thus defer lookup for resources until the requested resource value is actually required in order to construct an object.

还请注意,您可以使用

Also note that you can find the reference to the other resource better using FindResource. Try something like this (full working sample):

MainPage.xaml中:

<Window.Resources>
    <Color R="255" x:Key="styleRed" />
    <Style x:Key="abc" TargetType="StackPanel">
        <Setter Property="Background" Value="Blue" />
    </Style>
</Window.Resources>

MainPage.xaml.cs中:

Style style = this.FindResource("abc") as Style;
var r = this.FindResource("styleRed");

foreach (Setter s in style.Setters)
{
    if (s.Property == StackPanel.BackgroundProperty)
    {
        s.Value = r;
    }
}

这篇关于在代码中设置静态资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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