Arn*_*tte 17 c# wpf xaml app.xaml staticresource
我的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>
Run Code Online (Sandbox Code Playgroud)
我想改变BackgroundProperty我的代码mainpage.xaml.cs.
我试过用这个:
Style style = Application.Current.Resources["stackpanelBackground"] as Style;
style.Setters.SetValue(StackPanel.BackgroundProperty, "{StaticResource styleRed}");
Run Code Online (Sandbox Code Playgroud)
但我遇到了灾难性的失败异常.我认为这与此有关{StaticResource styleRed}.有一个更好的方法吗?
Pat*_*man 21
A StaticResource是静态的.应用程序编译后,您无法更改它们.
为此目的,有DynamicResource:
甲DynamicResource将初始编译过程中创建的临时表达,因此,直到所请求的资源值,以构建一个对象实际需要推迟资源查找.
另请注意,您可以更好地使用其他资源的参考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>
Run Code Online (Sandbox Code Playgroud)
在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;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么要修改样式而不是直接设置Background目标的-Property StackPanel?由于"本地值"的优先级高于"样式设置器",Background因此将使用您从后面的代码写入的值
手段:
(1)给你的stackpanel命名 x:Name="spBla"
(2)指定刷到Background的spBla(像spBla.Background=Application.Current.Resources["styleRed"] as SolidColorBrush;)
您可以在此处了解有关值优先级的更多信息:
http://msdn.microsoft.com/en-us/library/ms743230(v=vs.110).aspx