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