Xaml-位图UriSource-绝对路径有效,相对路径无效,为什么



我是一名WPF&Xaml-nob,对于控制台应用程序,我只需提供可执行文件的相对路径即可访问文件。对我来说,它似乎在xaml中不起作用。(底部的代码)
绝对路径完美工作。

在WPF应用程序的XAML中,是否可以通过简单地使用可执行文件目录的相对路径作为有效的UriSource来访问文件?如果是,如何?如果不是,为什么不

我发现了以下问题,他们正在讨论通过Visual Studio的"添加现有项"添加文件,所以这似乎是一个不同的问题。

如何将WPF BitmapImage UriSource属性设置为相对路径?

<Window.Icon>
  <!--absolute path works:-->
  <BitmapImage UriSource="C:LongPathSolutionFolderProjectFolderbinDebugpath4.ico" />
  <!--none of the following relative paths worked:-->
  <!--AppDomain.CurrentDomain.BaseDirectory returns the Debug-folder-->
  <!--<BitmapImage UriSource="path4.ico" />-->
  <!--<BitmapImage UriSource="../path4.ico" />-->
  <!--<BitmapImage UriSource="Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../../bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../Debug/path4.ico" />-->
</Window.Icon>

URI可能会令人困惑,因为它们既可以引用磁盘上的文件,也可以引用应用程序中的资源。因此,当你打算将应用程序中的资源放在磁盘上时,它可以是一个相对路径。

您可以使用siteoforigin权限强制使用相对文件URI。这个博客解释了更多,但这里有一个例子:

pack://siteoforigin:,,,/path4.ico

没有限定条件的相对路径在应用程序资源中查找引用的文件,如果路径应该是相对于可执行文件的,则可以使用pack://siteoforigin:,,,/path4.ico,请参阅MSDN上的Pack URI。

最新更新