我的作品里有几种风格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>
我想改变BackgroundProperty
在我的代码中mainpage.xaml.cs
.
我尝试使用这个:
Style style = Application.Current.Resources["stackpanelBackground"] as Style;
style.Setters.SetValue(StackPanel.BackgroundProperty, "{StaticResource styleRed}");
但我遇到了灾难性的失败异常。我认为这与{StaticResource styleRed}
。有一个更好的方法吗?
A StaticResource http://msdn.microsoft.com/en-us/library/ms750950.aspx是静态的。一旦应用程序编译完成,您就无法更改它们。
为此,有DynamicResource http://msdn.microsoft.com/en-us/library/ms748942.aspx:
A 动态资源将在初始编译期间创建临时表达式,从而推迟资源查找,直到实际需要请求的资源值才能构造对象。
另请注意,您可以使用更好地找到对其他资源的引用FindResource http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findresource%28v=vs.110%29.aspx。尝试这样的事情(完整的工作示例):
In MainPage.xaml
:
<Window.Resources>
<Color R="255" x:Key="styleRed" />
<Style x:Key="abc" TargetType="StackPanel">
<Setter Property="Background" Value="Blue" />
</Style>
</Window.Resources>
In 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)