What's the difference between StaticResource and DynamicResource in WPF?

前端 未结 8 2063
长发绾君心
长发绾君心 2020-11-22 12:33

When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources



        
8条回答
  •  长发绾君心
    2020-11-22 13:23

    I was also confused about them. See this example below:

    
    
        
            
            
        
    
    
        
            
        
    
    
    

    Here I have used dynamic resource for button and window and have not declared it anywhere.Upon runtime, the ResourceDictionary of the hierarchy will be checked.Since I have not defined it, I guess the default will be used.

    If I add the code below to click event of Button, since they use DynamicResource, the background will be updated accordingly.

    private void ButtonNew_Click(object sender, RoutedEventArgs e)
    {
        this.Resources.Add(  "PinkBrush"
                             ,new SolidColorBrush(SystemColors.DesktopColor)
                           );
    }
    

    If they had used StaticResource:

    • The resource has to be declared in XAML
    • And that too "before" they are used.

    Hope I cleared some confusion.

提交回复
热议问题