Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between Static Resource and Dynamic Resource in WPF

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.10k
    Comment on it

     

     Static Resource Dynamic Resource
    1. Static resource can be evaluated only once.    1.  Dynamic resource can be evaluated every time when needed.
    2. Static resource is loaded at compile time.      2. Dynamic resource is loaded at run time.
    3. Static resource can be uses the same value for entire life of the application.   3. Dynamic resource refer the value whenever it requires.
    4. It is used where the value may not be changed.    4. It is used where we have to change the value by code behind.

     

    Example of Static Resource Vs Dynamic Resource

     

    In XAML:

    <Window x:Class="WpfApplication.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApplication"
            mc:Ignorable="d"
            Title="MainWindow" Height="500" Width="500" Loaded="Window_Loaded">
        <Window.Resources>
            <SolidColorBrush Color="Red" x:Key="buttonRedBackground"/>
        </Window.Resources>
        <Grid>
            <WrapPanel Name="wrapPanel" Margin="120,0,0,0">
                <Button Name="Button1" Content="Button - Static Resource" Width="250" Height="50" Margin="10"  Background="{StaticResource buttonRedBackground}"/>
                <Button Name="Button2" Content="Button- Dynamic Resource" Width="250" Height="50" Margin="10" Background="{DynamicResource buttonRedBackground}" />
            </WrapPanel>
        </Grid>
    </Window> 

     

    In these I created a resource named "buttonRedBackground" which has "Red" background and assign these resource to both buttons. Then, in code behind I change the background of "buttonRedBackground" resource and change its background to green. 
    Then you will see in static resource button the colour is still red and in dynamic resource button colour is change to green.

     

    In Code Behind:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    	{
    		wrapPanel.Resources["buttonRedBackground"] = Brushes.Green;
    	}

     

    OUTPUT:

     

    Hope this sample will help you. Thanks 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: