简体   繁体   English

WPF中的StaticResources和DynamicResources有什么区别?

[英]What is the difference between StaticResources and DynamicResources in WPF?

What is the difference between StaticResources and DynamicResources in WPF? WPF中的StaticResources和DynamicResources有什么区别?

EDIT : This code in XAML file : 编辑:XAML文件中的此代码:

<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>

Dynamic resources are evaluated when you use them. 使用动态资源时将对其进行评估。 Static resources are evaluated at load time. 静态资源在加载时进行评估。

From MSDN : 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. StaticResource标记扩展通过在所有可用资源字典中查找该键的值来处理该键。 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. 相反,DynamicResource标记扩展通过创建表达式来处理键,并且该表达式在应用程序实际运行之前一直保持未评估状态,此时将评估该表达式并提供一个值。

There's a lot more detail there about when you should choose which option. 有关何时应选择哪个选项的更多详细信息。

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" 我收到此错误“找不到名为'{ComboBoxFocusVisual}的资源。资源名称区分大小写。标记文件中的对象'cmbItem'错误”

I think your ComboBoxFocusVisual resource is declared after ComboBoxStyle, so the StaticResource extension can't find it. 我认为您的ComboBoxFocusVisual资源是在ComboBoxStyle之后声明的,因此StaticResource扩展找不到它。 You should either declare it before you reference it, or reference it with a DynamicResource extension 您应该先声明它,然后再引用它,或者使用DynamicResource扩展名对其进行引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM