我有一个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‘更改为'DynamicResource',红色不再被拾取吗?
为什么会这样呢?
发布于 2015-01-12 02:45:53
您需要合并资源字典。将对包含CustomControl1样式的ResourceDictionary的引用添加到App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/AssemblyName;component/PathToResourceDictionary"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>在实际运行应用程序之前加载XAML期间,将解析StaticResource并将其分配给属性。它将只被分配一次,并且忽略对资源字典的任何更改。
DynamicResource在加载期间将表达式对象分配给属性,但直到运行时才实际查找资源,此时需要表达式对象的值。这会推迟查找资源,直到运行时需要它。一个很好的例子是对稍后在XAML中定义的资源的前向引用。另一个例子是直到运行时才会存在的资源。如果源资源字典发生更改,它将更新目标。
希望这能有所帮助。
https://stackoverflow.com/questions/27882671
复制相似问题