【发布时间】:2011-01-03 20:41:16
【问题描述】:
我有一个下载图片运行时的个人电影应用,我想显示图片而不是我放置的占位符图片(如果没有图片可用)
我发现应该可以解决问题的代码没有任何改变
我有这个 WPF 图像控件
<Image Name="MovieImage" Height="Auto" Width="Auto" Grid.Column="2" Grid.Row="0" Grid.ColumnSpan="2" Grid.RowSpan="4" Source="NoPhotoAvailable.jpg" />
然后我有
public void MovieList_SelectionChanged(Movie SelectedMovie)
{
this.SelectedMovie = SelectedMovie;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("/155.jpg", UriKind.RelativeOrAbsolute);
bi.EndInit();
Console.WriteLine(bi.UriSource.ToString());
MWV.MovieImage.Source = bi;
}
MWV 是图像控件所在的位置
图片放在apps文件夹中,命名为155.jpg,但什么都没有显示
我在这里发现了很多例子表明这应该非常接近解决方案,但显然不正确
解决方案:
public void MovieList_SelectionChanged(Movie SelectedMovie)
{
if (MovieCount == 0)
{
Console.WriteLine(MovieCount.ToString());
MWV.MovieImage.Source = new BitmapImage(new Uri("NoPhotoAvailable.jpg", UriKind.RelativeOrAbsolute));
}
else
{
this.SelectedMovie = SelectedMovie;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
string path = Path.Combine(Path.GetDirectoryName(typeof(MainWindowController).Assembly.Location), this.SelectedMovie.TMDBID.ToString() + ".jpg");
bi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
bi.EndInit();
Console.WriteLine(bi.UriSource.ToString());
MWV.MovieImage.Source = bi;
}
}
【问题讨论】:
-
您应该将
new BitmapImage(new Uri("NoPhotoAvailable.jpg", UriKind.RelativeOrAbsolute))存储在static字段中,这样您就不会一直重新加载相同的图像。