Xaml - Bitmap UriSource - 绝对路径工作,相对路径没有,为什么?

时间:2011-05-24 13:51:12

标签: wpf xaml relative-path

我是WPF& Xaml-noob,对于控制台应用程序,它对我来说只是提供了访问文件的可执行文件的相对路径。 它对我来说似乎不适用于xaml。 (代码在底部)
绝对路径完美无缺。

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

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

How can I set the WPF BitmapImage UriSource property to a relative path?

<Window.Icon>
  <!--absolute path works:-->
  <BitmapImage UriSource="C:\LongPath\SolutionFolder\ProjectFolder\bin\Debug\path4.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>

2 个答案:

答案 0 :(得分:11)

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

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

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

答案 1 :(得分:4)

没有限定条件的相对路径会在应用程序资源中查找引用的文件,如果路径应该与您可以使用pack://siteoforigin:,,,/path4.ico的可执行文件相关,请参阅Pack URIs on MSDN

相关问题