从具有设计时支持的静态成员获取ResourceDictionary源



我的基本目标是在dll中有一个ResourceDictionary,我可以通过ResourceDictionary.MergedDictionaries在另一个WPF项目中使用它。但我不想通过在引用应用程序的XAML中硬编码URI来引用ResourceDictionary,而是想引用一些将提供URI的静态成员。

我有一些简化的代码;工作";,但仅在运行时。在设计时,它会抛出错误,而我没有得到IntelliSense的支持。对于这个简化的示例,所有内容都在一个程序集中(没有单独的dll(。

Dic.xaml(我想参考的资源字典(:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush Color="Blue" x:Key="BlueBrush"/>
</ResourceDictionary>

Foo(用于保存具有URI的静态成员的模块(:
(VB.NET版本(

Public Module Foo
'[VBTest] is the name of assembly
Public ReadOnly Property URI As New Uri("pack://application:,,,/VBTest;component/Dic.xaml")
End Module

(C#版本(

public static class Foo
{
//[VBTest] is the name of assembly
public static Uri URI { get; } = new Uri("pack://application:,,,/VBTest;component/Dic.xaml");
}

最后,在应用程序中我想引用ResourceDictionary:的位置

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:VBTest">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="{x:Static local:Foo.URI}"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Border Width="100" Height="100" Background="{StaticResource BlueBrush}"/>
</Window>

在设计时,我得到了两个错误:

XDG0062 An error occurred while finding the resource dictionary "".
XDG0062 The resource "BlueBrush" could not be resolved.

但是,该项目的构建和运行都很好。并将显示预定的蓝色正方形。

问题是,我如何在设计时让它发挥作用?

谢天谢地,我找到了一个简单的解决方法。也许不是最漂亮的,但它很优雅。我从一个有点相关的问题的答案中获得了灵感。

通过创建继承自ResourceDictionary的自己的类,我可以更好地控制加载行为。这听起来很复杂,但实际上我所要做的就是将Source设置为构造函数的一部分,一切都正常工作。

以下内容被添加到代码文件中(Module/static classFoo外部(:

Public Class StylesResourceDictionary
Inherits ResourceDictionary
Public Sub New()
MyBase.New()
Source = URI
End Sub
End Class

注意,Source = URI引用了问题代码中的Foo.URI

然后XAML文件变成:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:VBTest">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<local:StylesResourceDictionary/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Border Width="100" Height="100" Background="{StaticResource BlueBrush}"/>
</Window>

bam,完全的设计时支持,无需将URI硬编码到引用应用程序中。ResourceDictionary及其URI的控制现在在dll的域中,并且可以使用专用类以(某种(静态方式引用。

最新更新