Question

What is the difference between StaticResources and DynamicResources in WPF?

EDIT : This code in XAML file :

<ComboBox Canvas.Left="14" Style="{StaticResource ComboBoxStyle}"
          Canvas.Top="137" Height="33" Name="cmbItem" Width="170"
          SelectionChanged="cmbItem_SelectionChanged">
    <ComboBoxItem>Name</ComboBoxItem>
    <ComboBoxItem>Age</ComboBoxItem>
</ComboBox>

below code is in resource dictionary file

<Style x:Key="ComboBoxStyle" TargetType="{x:Type ComboBox}">

    <Setter Property="FocusVisualStyle" Value="{StaticResource ComboBoxFocusVisual}"/>

    <Setter Property="Foreground" Value="#FF436B13"/>
</Style>
Was it helpful?

Solution

Dynamic resources are evaluated when you use them. Static resources are evaluated at load time.

From MSDN:

When you use a markup extension, you typically provide one or more parameters in string form that are processed by that particular markup extension, rather than being evaluated in the context of the property being set. The StaticResource Markup Extension processes a key by looking up the value for that key in all available resource dictionaries. This happens during loading, which is the point in time when the loading process needs to assign the property value that takes the static resource reference. The DynamicResource Markup Extension instead processes a key by creating an expression, and that expression remains unevaluated until the application is actually run, at which time the expression is evaluated and provides a value.

There's a lot more detail there about when you should choose which option.

OTHER TIPS

From your comment below Jon's answer :

i am getting this error "Cannot find resource named '{ComboBoxFocusVisual}'. Resource names are case sensitive. Error at object 'cmbItem' in markup file"

I think your ComboBoxFocusVisual resource is declared after ComboBoxStyle, so the StaticResource extension can't find it. You should either declare it before you reference it, or reference it with a DynamicResource extension

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top