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

前端 未结 8 2163
长发绾君心
长发绾君心 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:25

    1. StaticResource uses first value. DynamicResource uses last value.
    2. DynamicResource can be used for nested styling, StaticResource cannot.

    Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.

    
        
            
        
        
    
    

    In view:

    
        
            
                
                    
                
            
        
        
            

    StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.

    StaticResource StaticResource

    DynamicResource DynamicResource

    Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.

    StaticResource will throw an error when the root-level style (LightGreen) is removed.

提交回复
热议问题