开发者

Xaml - Bitmap UriSource - absolute path works, relative path does not, why?

开发者 https://www.devze.com 2023-03-08 05:24 出处:网络
I\'m, a WPF & Xaml-noob, for console applications it has worked for me to simply give the relative path to the executable to access a file.

I'm, a WPF & Xaml-noob, for console applications it has worked for me to simply give the relative path to the executable to access a file. It doesn't seem to work in xaml for me. (code at the bottom)

Absolute path works perfectly.

Is it possible in XAML in a WPF-application to access a file by simply using a relative path to the directory of your executable as a valid UriSource? If yes how and if not why not?

I found the following question, where they were talking about adding the file via Visual Studio's "Add existing item", so it seems like a different issue.

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/pa开发者_StackOverflowth4.ico" />-->
  <!--<BitmapImage UriSource="../bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../../bin/Debug/path4.ico" />-->
  <!--<BitmapImage UriSource="../Debug/path4.ico" />-->
</Window.Icon>


URIs can be confusing, as they can refer to both files on disk and resources in the application. So a relative path could be to a resource in the app, when you intend it to be on disk.

You can use the siteoforigin authority to force relative file URIs. This blog explains this more, but here an example:

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


Relative paths without qualifications look up the referenced file in the application resources, if a path should be relative to the executable you can use pack://siteoforigin:,,,/path4.ico, see Pack URIs on MSDN.

0

精彩评论

暂无评论...
验证码 换一张
取 消