Wpf 动态资源不工作
我有一个CustomControl库,其控件定义如下:Wpf 动态资源不工作,wpf,dynamicresource,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
<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”,红色将不再拾取
这是为什么?您需要合并资源字典。将对包含CustomControl1样式的ResourceDictionary的引用添加到App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/AssemblyName;component/PathToResourceDictionary"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
在应用程序实际运行之前加载XAML期间,将解析StaticResource并将其分配给属性。将只分配一次,并忽略对资源字典的任何更改
DynamicSource在加载期间将表达式对象分配给属性,但直到运行时请求表达式对象提供值时才实际查找资源。这将推迟查找资源,直到运行时需要它。一个很好的例子是对稍后在XAML中定义的资源的前向引用。另一个例子是直到运行时才存在的资源。如果源资源字典发生更改,它将更新目标
希望这能有所帮助。真奇怪。我应该指出,上面的代码是在一个库中,而不是在应用程序exe中。如果没有使用StaticResource做您提到的事情,它怎么会工作呢?我从未见过自定义控件库以这种方式合并(我认为向dll添加一个引用就足以拾取Themes\Generic.xaml),如果使用StaticResource,则在从自定义控件库加载之前会分配背景值。如果使用DynamicSource,则在加载期间将分配背景值,并且应用程序将在应用程序资源中查找DynamicSource。因此,您需要合并资源字典。但是在这个链接(请参阅动态资源查找)中,它表示如果在应用程序资源中找不到动态资源,则会搜索主题。