为此专门制作了一个新的测试项目,带有一个按钮和一个图像。 MyImage.png放置在项目的调试工作目录中,并且不包含在项目中。
这很好,并且指定了绝对路径:
private void BtnLoadFromFile_Click(object sender, RoutedEventArgs e)
{
Uri fileUri = new Uri("C:/blah/blah/blah/MyImage.png");
BitmapImage myimage = new BitmapImage(fileUri);
Imagebox.Source = myimage;
}
这不会显示任何具有相对路径的图像:
private void BtnLoadFromFile_Click(object sender, RoutedEventArgs e)
{
Uri fileUri = new Uri("MyImage.png", UriKind.Relative);
BitmapImage myimage = new BitmapImage(fileUri);
Imagebox.Source = myimage;
}
但是,如果我在最后一行设置断点,检查myimage的属性(它包含表明成功找到MyImage.png的数据),然后继续执行,相对路径确实可以工作。此时将显示图像。我正在使用Visual Studio 2019社区。
我很困惑为什么会这样。
这看起来像个虫子。解决方法是设置BitmapCacheOption.OnLoad
:
private void BtnLoadFromFile_Click(object sender, RoutedEventArgs e)
{
var fileUri = new Uri("MyImage.png", UriKind.Relative);
var myImage = new BitmapImage();
myImage.BeginInit();
myImage.UriSource = fileUri;
myImage.CacheOption = BitmapCacheOption.OnLoad;
myImage.EndInit();
Imagebox.Source = myImage;
}
或始终使用绝对URI:
private void BtnLoadFromFile_Click(object sender, RoutedEventArgs e)
{
var fileUri = new Uri(Path.Combine(Environment.CurrentDirectory, "MyImage.jpg"));
var myImage = new BitmapImage(fileUri);
Imagebox.Source = myImage;
}