ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • StaticResource and DynamicResource
    .NET/WPF 2010. 7. 20. 14:40
    반응형

    http://blogs.microsoft.co.il/blogs/davids/archive/2009/05/19/staticresource-and-dynamicresource.aspx

    StaticResource and DynamicResource

    So, whats the difference, and when should I use each?

    I am referring of course to the difference between the behavior of these two XAML elements:

          <Button Background="{StaticResource myBrush}">Static Resource</Button>

          <Button Background="{DynamicResource myBrush}">Dynamic Resource</Button>

    Where “myBrush” is defined as a resource in a scope that contains the buttons.

    The Difference

    Static resources are evaluated at compile time. Dynamic resources are evaluated at runtime, when they are needed. That includes whenever they are replaced with new objects.

    Note that if the resource itself is derived from Freezable, changes to the object will change the UI regardless of whether you used static or dynamic resource binding. (Brush, Animation and Geometry are all Freezable).

    The following demonstration should make this clear.

    Demonstration

    The following code demonstrates this behavior:

    XAML:

    <Window x:Class="DynamicStyles.Window1"

           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

           Title="Window1"

           Height="300"

           Width="300"

           Loaded="Window_Loaded">

       <Window.Resources>

          <SolidColorBrush Color="Red"

                          x:Key="myBrush"></SolidColorBrush>

       </Window.Resources>

       <StackPanel>

          <Button Background="{StaticResource myBrush}">Static Resource</Button>

          <Button Background="{DynamicResource myBrush}">Dynamic Resource</Button>

          <Button Click="ChangeBrush_Click">Change brush</Button>

          <Button Click="ChangeResource_Click">Change resource</Button>

       </StackPanel>

    </Window>

    C#

    using System;

     

    namespace DynamicStyles

    {

        /// <summary>

        /// Interaction logic for Window1.xaml

        /// </summary>

        public partial class Window1 : Window

        {

            public Window1()

            {

                InitializeComponent();

            }

     

            SolidColorBrush myBrush;

            SolidColorBrush anotherBrush;

     

            private void Window_Loaded(object sender, RoutedEventArgs e)

            {

                myBrush = Resources["myBrush"as SolidColorBrush;

                anotherBrush = new SolidColorBrush(Colors.Blue);

            }

     

            private void ChangeBrush_Click(object sender, RoutedEventArgs e)

            {

                if (myBrush.Color == Colors.Red)

                {

                    myBrush.Color = Colors.Blue;

                }

                else

                {

                    myBrush.Color = Colors.Red;

                }

            }

     

            private void ChangeResource_Click(object sender, RoutedEventArgs e)

            {

                if (FindResource("myBrush"as SolidColorBrush == myBrush)

                {

                    Resources["myBrush"] = anotherBrush;

                }

                else

                {

                    Resources["myBrush"] = myBrush;

                }

            }

        }

    }

    In this application, the top two buttons have no function - they just bind their Background property to a resource whose resource key is “myBrush”. The first button binds statically, the other dynamically.

    The myBrush member is initialized in the Window_Loaded handler to the resource whose resource key is “myBrush”.

    The third button is linked to ChangeBrush_Click which changes the Color property of myBrush, toggling between Red and Blue.

    The fourth button is linked to ChangeResource_Click which changes the entry in the Resource dictionary, toggling between the original brush and another that’s blue.

    If you run the application and press the third button, both of the two top buttons change their color because myBrush is a Freezable object and changes in its properties are propagated to the underlying presentation layer.

    If you then press the fourth button, only the second button changes color. This is because static resources are resolved once, at compile time. Dynamic resources, on the other hand, are evaluated at run time, in particular when the resource entry to which they point is replaced with another.

    If you now press the third button again the background of the first button (Static Resource) changes but not the second (Dynamic Resource). This is because the second button, being dynamically resolved, no longer points to myBrush which is the object that is being modified by ChangeBrush_Click.

    Play around with it to see.

    Choosing between DynamicResource and StaticResource

    1. Static Resource requires less run time CPU so it will usually be your first choice.
    2. An exception to this rule is if you want to speed up the loading process of the application. Static resources are all assigned when the application loads. If there are many such assignments, loading may be slow. Dynamic resources, on the other hand, will only be evaluated when needed, so the initial loading of your main window may be quicker with dynamic resources.
    3. If your resources are unknown at compile time, use Dynamic Resource. There are two typical situations when this might be the case:
      • You want to change the theme of your application at run time (for instance you might offer the user the option to personalize the application). In this case you can modify resource dictionary entries in the application and all dynamic resources will change their look.
      • You are binding to system resources like current Windows colors or fonts. If you want your application to react to changes in the system settings associated with these resources, they should be bound dynamically.
    Published Tuesday, May 19, 2009 1:51 AM by David Sackstein

    Comments

    # re: StaticResource and DynamicResource

    Thursday, March 25, 2010 3:25 PM by tzvi

    excellent post ! פוסט נהדר

    Leave a Comme

    반응형

    댓글

Designed by Tistory.