2009-09-18 87 views
12

我在設置我的Wpf應用程序中的圖像源時出現問題。我有其中源被綁定到DataContext對象的SourceUri財產,像這樣的圖片:Wpf - 相對圖像源路徑

<Image Source="{Binding SourceUri}"></Image> 

現在,我不知道是什麼在我的對象的SourceUri屬性設置。設置完整的絕對路徑(「c:/etc/image.jpg」)它很好地顯示,但顯然我想設置相對路徑。我的圖像存儲在與我的應用程序文件夾位於同一文件夾中的資源文件夾中。最終,這些圖像可能來自任何地方,因此將它們添加到項目中確實不是一種選擇。

我已經嘗試了相對於應用程序文件夾以及相對於工作路徑(debug-folder)的路徑。還嘗試過使用「pack:// ..」語法,但沒有運氣,但讀到這不會有任何問題。

任何我應該嘗試的提示?

回答

9

也許你可以讓你的DataContext對象的SourceUri屬性有點聰明,並確定應用程序文件夾是什麼,並返回一個絕對路徑。例如:

public string SourceUri 
{ 
    get 
    { 
     return Path.Combine(GetApplicationFolder(), "Resources/image.jpg"); 
    } 
} 
+0

當然 - 的作品 - THX!找不到找到應用程序文件夾的好方法,所以現在感覺有點怪異..在.Net中是否有GetApplicationFolder()?找不到一個..但不應該相對路徑引用以某種方式工作?然後這些將相對於應用程序根文件夾?沒有? – stiank81 2009-09-18 20:03:48

+1

嘗試Path.GetDirectoryName(Assembly.GetExecutingAssembly()。位置); – 2009-09-18 20:05:43

+0

這給了我一樣的,我正在使用,「Path.GetFullPath(」。「),但我想後者取決於工作文件夾,所以隨着你的建議,我得到了更多的問題,但這個,但我會弄明白的。Thx請注意! – stiank81 2009-09-18 20:38:34

3

Environment.CurrentDirectory會顯示您的.exe文件存儲在文件夾(也就是除非你手動設置.CurrentDirectory - 但是我們可以假設你已經知道它在哪裏)。

17

有一個在System.IO.Path一個方便的方法,可以在這方面幫助:

return Path.GetFullPath("Resources/image.jpg"); 

這應該返回「C:\文件夾\ MoreFolders \資源\ image.jpg的」或者是完整路徑是在你的情況下。它將使用當前工作文件夾作爲起點。

Link to MSDN documentation on GetFullPath.

+2

這真是太棒了 - 如果我想提供自己的完整路徑,它仍然有效。 – paddy 2013-07-11 03:43:38

7

<Image Source="pack://application:,,,/{Binding ChannelInfo/ChannelImage}"> 

嘗試一番折騰次後
<Image Source="pack://siteoforigin:,,,/{Binding ChannelInfo/ChannelImage}"> 

<Image Source="/{Binding ChannelInfo/ChannelImage}"> 

我解決了這個實現自己的轉換ER:

C#的一面:

public class MyImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     string path= (string)value; 

     try 
     { 
      //ABSOLUTE 
      if (path.Length > 0 && path[0] == System.IO.Path.DirectorySeparatorChar 
       || path.Length > 1 && path[1] == System.IO.Path.VolumeSeparatorChar) 
       return new BitmapImage(new Uri(path)); 

      //RELATIVE 
      return new BitmapImage(new Uri(System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + path)); 
     } 
     catch (Exception) 
     { 
      return new BitmapImage(); 
     } 

    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

XAML的一面:

<UserControl.Resources> 
    <local:ImageConverter x:Key="MyImageConverter" /> 
    (...) 
</UserControl.Resources> 

<Image Source="{Binding Products/Image, Converter={StaticResource MyImageConverter}}"> 

乾杯,

塞爾吉奧