WPF 使用相对路径从程序集中的任何位置访问资源

WPF accessing a resource from anywhere in the assembly using relative path

在我的应用程序中,我创建了大量自定义控件,然后我将在不同 windows 中使用这些控件。我的项目结构如下所示:

我正在创建存储在 Controls 文件夹中的 classes(控件)。如果我想在控件中使用图像,我可以这样访问它:

new Uri("../Resources/my_image.png", UriKind.Relative)

虽然有时我想在多个 windows 中使用相同的控件,但有时这些 windows 存储在不同的文件夹中。如果我使用存储在另一个文件夹中的说 Window3 中的控件,则不会显示图像。

如果我将 Uri 更改为:(在路径中添加另一个 "go back" 命令)

new Uri("../../Resources/my_image.png", UriKind.Relative)

图像在Window3中显示,但在Window1或Window2中不显示。

有没有办法创建相对于主要可执行文件而不是相对于显示控件的 window 的路径?

编辑: 我忘了提一个重要的部分。因为在启动这个应用程序时我只是在学习如何使用 WPF,所以我搞砸了一件事。我的资源文件夹不在包含主要可执行文件的文件夹中。

我的文件结构如下所示:

我尝试使用大家建议的路径:

 new Uri("pack://application:,,,/../../my_image.png", UriKind.RelativeOrAbsolute)

但我遇到了异常:

Cannot locate resource 'my_image.png'.

我可以尝试重新定位 Resources 文件夹,但它会弄乱所有其他路径。有什么方法可以在 "pack" uri 的文件夹结构中进入 "back" 吗?如果没有,什么是重新定位文件夹以免所有路径混乱的最佳方法?

简答:使用包 URI 表示法。

示例:

您的 URI 看起来类似于:pack://application:,,,/Resources/my_image.png 无论您在 XAML 中的什么地方使用它。

文档:

MSDN - Pack URIs in WPF

使用Pack Uri Scheme

Resource File Pack URIs - Local Assembly

The pack URI for a resource file that is compiled into the local assembly uses the following authority and path:

Authority: application:///.

Path: The name of the resource file, including its path relative to the root of the local assembly project folder.

The following example shows the pack URI for a XAML resource file that is located in the root of the local assembly's project folder:

pack://application:,,,/ResourceFile.xaml

The following example shows the pack URI for a XAML resource file that is located in a subfolder of the local assembly's project folder:

pack://application:,,,/Subfolder/ResourceFile.xaml

使用 "pack" uri...所以您将使用:

pack://application:,,,/Resources/my_image.png

像这样:

new Uri("pack://application:,,,/Resources/my_image.png");

从您的任何 Windows/Controls 中引用您的 "image"。

如果您还有其他 "projects"/"assemblies"...您希望能够引用该资源,请使用:

pack://application:,,,/AssemblyNameContainingResource;component/Resources/my_image.png

并且当您在 Resource 文件夹中添加图像时....请确保使用 Resource 作为 Build Action

SubModuleA这样的子模块中,在SubModuelA的视图模型中,当你想访问SubModuelA的资源文件而不是启动的项目时。

例如,资源文件的目录是StartApp/SubModuelA/Resource/Data/JsonData.json,在SubModuelA的视图模型中它的路径应该是

string jsonFile="../../../SubModuleA/Resource/Data/JsonData.json"

我验证了这一点并将数据写入 jsonFile。