问题描述
|
我是WPF和Xaml-noob,对于控制台应用程序,它对我来说只是简单地给出可执行文件的相对路径以访问文件。
对于我来说,它似乎在xaml中不起作用。 (底部代码)
绝对路径完美运行。
在WPF应用程序的XAML中,是否可以仅通过使用可执行文件目录的相对路径作为有效UriSource来访问文件?如果是,如何,如果不是,为什么不?
我发现了以下问题,他们在谈论如何通过Visual Studio的“添加现有项”添加文件,因此似乎是一个不同的问题。
如何将WPF BitmapImage UriSource属性设置为相对路径?
<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>
解决方法
URI可能令人困惑,因为它们既可以引用磁盘上的文件,也可以引用应用程序中的资源。因此,当您打算将其放在磁盘上时,相对路径可能是应用程序中的资源。
您可以使用siteoforigin授权来强制相对文件URI。该博客对此进行了更多解释,但这里有一个示例:
pack://siteoforigin:,/path4.ico
,没有限定条件的相对路径在应用程序资源中查找引用的文件,如果路径相对于可执行文件,则可以使用“ 2”,请参阅MSDN上的Pack URI。