WPF Image.Source什么都不做

时间:2017-07-06 07:11:02

标签: c# wpf

我一直在尝试将代码中的 Image.Source 设置为这样的相对路径:

IMG_3.Source = new BitmapImage(new Uri("./Sprites/Layout/image1.png", UriKind.Relative));

如果我使用非现有路径,程序会崩溃。

但是这条路径存在并且像Rectangle中的 .Fill 一样工作。 这有什么不对吗?

2 个答案:

答案 0 :(得分:1)

我认为这里没有错。请尝试使用完整路径。 .Last()是Linq,所以如果你不想使用它,只需对count-1做同样的事情。

string exe = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Split('\\').Last();
IMG_3.Source = new BitmapImage(new Uri(System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.Length - exe.Length) + "/Sprites/Layout/image1.png"));

答案 1 :(得分:1)

如果图像文件位于与应用程序可执行程序集路径相关的文件夹结构中,则应按Content File Pack URIs加载它们,如下所示:

try
{
    IMG_3.Source = new BitmapImage(
        new Uri("pack://application:,,,/Sprites/Layout/image1.png"));
}
catch
{
    IMG_3.Source = fallbackImage;
}