gpt4 book ai didi

c# - 在代码中设置静态资源

转载 作者:可可西里 更新时间:2023-11-01 02:58:43 27 4
gpt4 key购买 nike

我的 App.xaml 文件中有一些样式:

<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

我试过用这个:

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

但是我得到了一个灾难性的失败异常。我认为这与 {StaticResource styleRed} 有关。有更好的方法吗?

最佳答案

A StaticResource是静态的。一旦应用程序编译完成,您就无法更改它们。

为此,有 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.

另请注意,您可以使用 FindResource 更好地找到对其他资源的引用.尝试这样的事情(完整的工作示例):

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

关于c# - 在代码中设置静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27106822/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com