【问题标题】:Changing wpf image source to a jpg on runtime that is not a resource在运行时将 wpf 图像源更改为不是资源的 jpg
【发布时间】: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 字段中,这样您就不会一直重新加载相同的图像。

标签: c# .net wpf


【解决方案1】:

从路径中删除 /
/ 开头的路径是绝对 路径,因此您的代码会在驱动器的根目录中查找名为155.jpg 的文件。

【讨论】:

  • @"c:/155.jpg" 显示图像,但 "155.jpg" 没有显示任何内容,我需要第二个才能工作,因为我将使用 this.SelectedMovie.TMDBID.ToString( ) + ".jpg" 只是在此处输入示例以避免混淆
  • 在应用程序文件夹中,因此我不明白为什么“155.jpg”不起作用。 C:\ 只是为了测试我是否可以显示图像
  • 在项目文件夹还是输出路径?
  • MovieDB2\bin\Debug 所以在与可执行文件相同的文件夹中
  • 你需要使用Path.GetDirectoryNameAssembly.Location是文件的路径)。在你的代码中,你不需要.ToString(),你应该调用Path.Combine
猜你喜欢
  • 2010-10-30
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
相关资源
最近更新 更多