Search This Blog

Friday, November 29, 2013

WPF Resources - Static and Dynamic example

WPF > Resources

 
A resource is an object. This object is reused in different places in an application.
  • XAML resources (brushes, styles)
  • data files
StaticResource 
It is assigned to the property during the loading of the XAML and no need for application to run. It is assigned only once.

DynamicResource
It is lookup for the resource in runtime.

Example

You see in this image static resource is loaded during design XAML:

 
XAML:


<Window x:Class="WpfApplication4.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">
    <Window.Resources>
        <SolidColorBrush x:Key="brush" Color="Red" />
    </Window.Resources>
    <Grid>
        <Grid.Resources>
            <SolidColorBrush x:Key="bgcolor" Color="Green"/>
        </Grid.Resources>

        <TextBlock x:Name="txt" Background="{StaticResource bgcolor}"  Margin="113,92,145,129">StaticResource</TextBlock>

        <Button x:Name="btn" Content="Dynamic Resource" HorizontalAlignment="Left" VerticalAlignment="Top" Width="114" Click="Button_Click"/>
    </Grid>
</Window>

C# Code:

   this.btn.SetResourceReference(BackgroundProperty, "brush");
Dynamic resource is loaded in runtime