Static and Dynamic Resource
A resource can be referenced as either static or dynamic resource. This can be done by using either Static resource markup extension or Dynamic resource markup extension. You can go through my post on Markupextension in WPF for more information about markup extension.
- The major difference between static and dynamic resources is “static resource will evaluate the resource only once while dynamic resource will be evaluated every time the resource needed”.
- Dynamic resource has more performance overhead than static resources because it look up for resources every time it requested or needed.
- Static resource is faster but it takes little more time to load page or window than dynamic resource because dynamic resources are loaded when you actually used those.
- If resource is defined on the element’s resources and the same element property is using the resource defined inside its resources then static resource not applied because it should appears afterwards. The same thing is valid for dynamic resource. Let’s have a look on below code snippet.
Below code gives compile time error.
<Grid Background="{StaticResource lightBlueColor}">
<Grid.Resources>
<SolidColorBrush Color="LightBlue" x:Key="lightBlueColor"/>
</Grid.Resources>
</Grid>
The same is valid for dynamic resource
<Grid Background="{DynamicResource lightBlueColor}">
<Grid.Resources>
<SolidColorBrush Color="LightBlue" x:Key="lightBlueColor"/>
</Grid.Resources>
</Grid>
Below example gives you clear picture about Static and Dynamic resource markup extension.
XAML
<Window.Resources>
<SolidColorBrush Color="LightBlue" x:Key="buttonBackground" />
</Window.Resources>
<StackPanel Name="stkPanel">
<Button Name="Button1" Content="Button1"
Width="150" Height="40" Margin="5"
Background="{StaticResource buttonBackground}"/>
<Button Name="Button2" Content="Button2"
Width="150" Height="40" Margin="5"
Background="{DynamicResource buttonBackground}"/>
<Button Name="Button3" Content="Button3"
Width="150" Height="40" Margin="5"
Background="{StaticResource buttonBackground}"/>
</StackPanel>
Code behind
void StaticAndDynamicResources_Loaded(object sender, RoutedEventArgs e)
{
stkPanel.Resources["buttonBackground"] = Brushes.Yellow;
}
Output
No comments:
Post a Comment