【问题标题】:Xaml - Bitmap UriSource - absolute path works, relative path does not, why?Xaml - 位图 UriSource - 绝对路径有效,相对路径无效,为什么?
【发布时间】:2011-05-24 13:51:12
【问题描述】:

我是 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>

【问题讨论】:

    标签: wpf xaml relative-path


    【解决方案1】:

    URI 可能会造成混淆,因为它们可以引用磁盘上的文件和应用程序中的资源。因此,当您打算将其放在磁盘上时,相对路径可能指向应用程序中的资源。

    您可以使用siteoforigin 权限来强制使用相关文件 URI。 This blog 对此进行了更多解释,但这里是一个示例:

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

    【讨论】:

    • pack:// URI 方案在 Metro 执行上下文之外是否相关?该方案是否与在 Windows 7 下运行的 WPF 应用程序相关?所有这些文档链接都表明该方案仅与 Metro 相关,但我们在 Windows 7 下遇到了这个问题。
    • @ardave - 这个答案是 WPF 特有的,在 Metro 或 WinRT 出现之前就已经发布了。
    【解决方案2】:

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

    【讨论】:

    • 这对于调用文件“上方”的相对路径如何工作?例如,如果有 2 个名为 path4.ico 的文件。是否有分层搜索会返回“深度距离”意义上最接近的文件?
    • @Mechandrius 我很确定你必须直接指向文件,所以如果你想上一层,路径以../path4.ico结尾,上两层你会得到../../path4.ico。不过从未尝试过。
    猜你喜欢
    • 2012-05-20
    • 1970-01-01
    • 2015-09-20
    • 2020-11-16
    • 2012-05-04
    • 1970-01-01
    • 2012-09-15
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多