Windows Presentation Foundation (WPF) resources provide a simple way to reuse commonly defined objects and values. Resources in WPF allow you to set the properties of multiple controls at a time. For example, you can set the background property on several elements in a WPF application using a single resource.
The best way of defining the resources is on a Window or Page element level. Any resource that you define for an element also applies to their child elements of that element.
If you define a resource for the grid element, then the resource applies only to the child elements of the grid element.
Syntax for resources in WPF is as follows:
<elementName propertyName="{markupExtension keyName}">
<!-Content -->
</elementName>
There are two types of resource, namely,
- Static Resource
- Dynamic Resource
Static Resource
We should use the StaticResource markup extension to define the resource as a static resource. The value of StaticResource is determined at the time of loading.
- <Grid.Resources>
- <SolidColorBrush x:Key="lblbgcolor" Color="Blue"/>
- </Grid.Resources>
- <Label Name="lbl" Margin="71,44,77,0" Background="{StaticResourcelblbgcolor}" Height="49" />
Dynamic Resource
Dynamic Resource we use in a situation where we want to change the value of property at run time.
- <Window.Resources>
- <SolidColorBrush x:Key="brush" Color="Red" />
- </Window.Resources>
- <Button x:Name="btn" Content="Click Me" Click="Button_Click" Background="{DynamicResource brush}" Height="100" Width="100" />
Open Code behind and add the following code snippet:
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- this.btn.SetResourceReference(BackgroundProperty, "brush");
- }