DynamicResource无效

时间:2015-01-11 00:24:08

标签: wpf dynamicresource

我有一个CustomControl库,其控件定义如下:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary1">

<SolidColorBrush x:Key="Test"
                 Color="Red" />

<Style TargetType="{x:Type local:CustomControl1}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                <Border Background="{StaticResource Test}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

哪种方法正常。

但是,如果我改变了'StaticResource&#39;要动态资源&#39;红色不再被选中?

为什么会这样?

1 个答案:

答案 0 :(得分:1)

您需要合并资源字典。添加对包含CustomControl1到App.xaml的样式的ResourceDictionary的引用:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/AssemblyName;component/PathToResourceDictionary"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

在加载实际运行应用程序之前发生的XAML期间,将解析StaticResource并将其分配给该属性。它将仅被分配一次,并且忽略对资源字典的任何更改。

DynamicResource在加载期间将一个Expression对象分配给属性,但在运行时要求Expression对象输入值时,实际上不会查找资源。这会延迟查找资源,直到在运行时需要它为止。一个很好的例子是对稍后在XAML中定义的资源的前向引用。另一个例子是直到运行时才会存在的资源。如果源资源字典已更改,它将更新目标。

希望这会有所帮助。