StaticResource vs DynamicResource

By Michael Detras

We often see StaticResource and DynamicResource in XAML files, used in binding to resources. There are some differences between the two that we might want to take note of.

Let’s say we have the following Window. It contains a Grid control where its background is bound to a LinearGradientBrush resource by using StaticResource.

<Window x:Class="WpfApplication1.MainWindow"
         
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         
Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
         <LinearGradientBrush x:Key="MyBrush" StartPoint="0,0" EndPoint="0,1">
            <GradientStop Color="White" Offset="0"/>
            <GradientStop Color="Blue" Offset="1"/>
        </LinearGradientBrush>
    </Window.Resources>
     <Grid
        
Background="{StaticResource ResourceKey=MyBrush}">        
    </Grid>
</Window>

This will compile successfully. If we removed the LinearGradientBrush resource, compilation will result to the following warning: The resource "MyBrush" could not be resolved. The application will still run but then we’ll get an exception message like this: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '4' and line position '28'. If we started using DynamicResource instead of StaticResource, we’ll still get the same warning. However, unlike when using StaticResource, the application will run without any exceptions thrown.
Let’s say we added a Loaded event handler for the Window and changes the MyBrush resource so that the brush is colored red. This is shown in the code snippet below.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var window = sender as Window;
    var linearGradientBrush = new LinearGradientBrush
    {
       StartPoint = new Point(0, 0),
       EndPoint = new Point(0, 1),
       GradientStops = new GradientStopCollection
        {
             new GradientStop { Color = Colors.White, Offset = 0 },
            new GradientStop { Color = Colors.Red, Offset = 1}
        }
     };
    window.Resources["MyBrush"] = linearGradientBrush;
}

When StaticResource is used, the Background color of the Grid will stay the same, which is color blue. However, when DynamicResource is used, the Background color will turn to red. So when do you need to use a StaticResource and when do you need a DynamicResource? Basically, DynamicResource is used for resources that change value at runtime. For example, if the application theme can be changed, then it might be better to use a DynamicResource. If changing resources at runtime isn’t a concern (or at least resource interdependencies are not complex), then using StaticResource should be fine.

StaticResource vs DynamicResource  (2899 Views)