Using DynamicResources in WPF

DynamicResource: DynamicResources are resolved at runtime. Use DynamicResources when the value of the resource could change during the lifetime of the Application.


I will show you an example regarding DynamicResource.



<SolidColorBrush x:Key="brush" Color="BlueViolet"></SolidColorBrush>

<Style TargetType="Border" x:Key="background">

<Setter Property="Background" Value="Green"></Setter>




In my WPF application page I've one textbox and two ellipses. In Window.Resources I defined the SolidColorBrush and the Style properties.

In above code you can observe x: Key attribute. x: Key uniquely identifies elements that are created and referenced in a XAML-defined dictionary.


Here I'm using above resources. Have a look at below code. 

You can use this syntax in xaml design page: {DynamicResource x:keyName}




<Border Style="{StaticResource background}">

<DockPanel Height="360" Width="312">                

<Button x:Name="button" Content="Click" Click="Button_Click" Background="CadetBlue" Height="40" Width="63" />






And in code behind page (.xaml.cs), I write this code in button click event.


private void Button_Click(object sender, RoutedEventArgs e)


    this.button.SetResourceReference(BackgroundProperty, "brush");



Run the page and you can see the color change of the button after you click on it.


Result window looks like this.




In my very next article, I will explain you about DynamicResource with Animation.

Hope you like this article; let me know if you have any queries.