Dynamic Resources in WPF Application

Updated on     Kisan Patel

Dynamic resources are those resources that can be changed after they are referenced for the first time.

A dynamic resource is applied using the DynamicResource markup extension, which processes a key by creating an expression. This expression remains unchecked until the application is actually run.

<Button Content="Change color" Width="100" Height="30" Background="{DynamicResource myBrush}"/>

The major difference between the static resources and dynamic resources is that static resource is loaded at compile time and dynamic resource is loaded at run time.

MainWindow.xaml

<Window x:Class="WPFResourceDemo.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">
     <Grid>
        <Grid.Resources>
           <SolidColorBrush x:Key="myBrush" Color="Red"></SolidColorBrush>
        </Grid.Resources>
        <Button Content="Change color" Width="100" Height="30" Background="{DynamicResource myBrush}"/>
     </Grid>
</Window>

The output of the above XAML code will be:

wpf-dynamic-resource


WPF

Leave a Reply