Iv. Static Resources (StaticResource) and dynamic resources (DynamicResource)
A resource can be referenced as either a static resource or a dynamic resource. This is done by using the StaticResource markup extension or the DynamicResource markup extension.
Typically, resources that do not need to be changed at run time use static resources, while resources that need to be changed at run time use dynamic resources. Dynamic resources need to use more system overhead than static resources. For example, the following example:
1: <window x:class= "Wpfresource.staticanddynamicresource"
2:xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3:xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"
4:title= "Staticanddynamicresource" height= "width=" >
5: <Window.Resources>
6: <solidcolorbrush x:key= "Buttonbrush" color= "Red"/>
7: </Window.Resources>
8:
9: <StackPanel>
Ten: <button margin= "5" content= "Static Resource button A" background= "{StaticResource Buttonbrush}"/>
One: <button margin= "5" content= "Static Resource button B" background= "{StaticResource Buttonbrush}" >
<Button.Resources>
<solidcolorbrush x:key= "Buttonbrush" color= "Yellow"/>
: </Button.Resources>
: </Button>
: <button margin= "5" content= "Change Button Resource" click= "Button_Click"/>
<button margin= "5" content= "Dynamic Resource button A" background= "{DynamicResource Buttonbrush}"/>
<button margin= "5" content= "Dynamic Resource button B" background= "{DynamicResource Buttonbrush}" >
: <Button.Resources>
<solidcolorbrush x:key= "Buttonbrush" color= "Yellow"/>
</Button.Resources>
</Button>
: </StackPanel>
: </Window>
1:private void Button_Click (object sender, RoutedEventArgs e)
2: {
3:solidcolorbrush brush = new SolidColorBrush (colors.green);
4:this. resources["Buttonbrush"] = brush;
5:}
The above examples are shown at run time as follows:
Click the "Change button Resource" button, the results displayed are: