WPF Dispay image from relative location

放肆的年华 提交于 2019-12-13 03:59:19

问题


I would like to display an image on my dialog which could be located in a directory relative to the one the .exe is located in, e.g.

project
- data
 -- logo  //<-- that's where the image is located
-bin      //<-- that's where the .exe is in

A default image should be included in the .exe but on displaying the dialog, the \data\logo directory should be checked first and if an image with the given filename could be found there that one should be used for display instead of the one that is inside the .exe.

Any ideas on how to do this?

Thanks,

tabina


回答1:


Use the pack URI

pack://application:,,,/ReferencedAssembly;component/data/logo/image.png



回答2:


As he asks for a folder relative to the exe, i suggest he means the logo should be located inside the filesystem (e.g. c:\program files\MyApp\data\logo). So I would check if the file exists with

File.Exists("/data/logo/logo.png")

If it returns false, you could load your embedded resource.

//Edit

If you use this snippet in your Visual Studio IDE the path is located at

<Project directory>/bin/debug/data/logo



回答3:


what I am doing now is

  // set the logo
  string path = Environment.CurrentDirectory + "\\data\\logo\\logo.gif";
  var uri = new Uri(path, UriKind.Absolute);
  try
  {
    this.myImg.Source = new BitmapImage(uri);
  }
  catch (Exception e)
  {
    this.myImg.Source = new BitmapImage(new Uri(@"pack://application:,,,/myAssemblyName;component/Images/logo.gif"));
  }

This works pretty well, but what I don't like about this is that it is all written in the code-behind. I would rather have it more re-usable. Is there a way to put it all into a template and apply it to viewboxes/images?

Thanks,

tabina



来源:https://stackoverflow.com/questions/10311433/wpf-dispay-image-from-relative-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!