How to Access the Resources from code behind in WPF application

Updated on     Kisan Patel

This WPF tutorial will explain you how to access the resources from code behind in a WPF application?

First add the below line of XAML code to MainWindow.xaml file:

<Window x:Class="WPFResourceDemo.MainWindow"
    Title="MainWindow" Height="350" Width="525">
           <SolidColorBrush x:Key="myBrush" Color="Red"></SolidColorBrush>
           <SolidColorBrush x:Key="myNewBrush" Color="Green"></SolidColorBrush>
        <Button Content="Change color" Width="100" Height="30" Background="{DynamicResource myBrush}" Click="Button_Click_1"/>

To access the resource through the code, you need to add the code in the code-behind file. To do so, add the below code to the MainWindow.xaml.cs file:

private void Button_Click_1(object sender, RoutedEventArgs e)
     Control button = sender as Control;
     button.Background = button.FindResource("myNewBrush") as Brush;

When you run the code, you can see that a Button control is added to the window. When you click the Button control, the color of the control changes to the color specified in your XAML code.

The output of the above code will be:



Leave a Reply