基于FileName在ListBox中显示图像

时间:2013-06-10 22:01:42

标签: c# wpf image listbox

我正在尝试在Image中为从数据库返回的每个Filetype显示ListBox。以下是我正在使用的代码。我认为我的问题是我正在尝试将属性从db传递到DirectoryInfo属性。一切都是正确的,直到我到达FileImage = di.GetFiles();然后我得到一个异常无法在bin文件夹中找到文件。实现这一目标的最佳方法是什么?谢谢你的回复。

转换器存储在与其他转换器(不在代码后面)的文件夹中。

public class ConvertFileImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value as string == string.Empty) return null;

            var file = @"Media/file_" + value.ToString().Substring(1) + ".png";
            ImageSource src = new BitmapImage(new Uri(file, UriKind.Relative));
            return src;
        }

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

存储db

文件的类
public class FilesFromDb
{
     public int Id { get; set; }
     public byte[] Data { get; set; }
     public string FileName { get; set; }
}

列表框绑定到

的属性
public ObservableCollection<FilesFromDb> Files
{
     get
     {
          return mFiles;
     }
}

从文件名中获取图像的属性

public FileInfo[] FileImage { get; set; }

我正在尝试使用foreach循环从数据库中获取Filename并将其用于目录,我在这里失败了。

foreach (var imagetype in Files)
                    {
                        var di = new DirectoryInfo(imagetype.FileName);
                        FileImage = di.GetFiles();


                    }

然后我绑定了xaml中的转换器

<converters:ConvertFileImage x:Key="ConvertFileImage"/>

这是一个列表框项目模板,其中包含列表框ItemsSource =“{Binding Files}”

 <Grid Grid.Row="0" Grid.RowSpan="2" Grid.Column="0">
      <Image Source="{Binding Extension, Converter={StaticResource ConvertFileImage}}"  HorizontalAlignment="Left" />
  </Grid>

如果文件存储在本地,我可以使用类似的东西

 var di = new DirectoryInfo("c:/FilesFolder");  // I think that would work, but not using a property from db

1 个答案:

答案 0 :(得分:2)

在重新阅读你的问题几次后,我想我明白了你要去的地方。我相信你的ConvertFileImage应该看起来更像这样:

public class ConvertFileImage : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     {
         if (value as string == string.Empty) return null;

         var file = @"Media/file_" + Path.GetExtension(value.ToString()) + ".png";
         ImageSource src = new BitmapImage(new Uri(file, UriKind.Relative));
         return src;
    }

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

然后你的绑定应该传递文件名:

<Grid Grid.Row="0" Grid.RowSpan="2" Grid.Column="0">
    <Image Source="{Binding FileName, Converter={StaticResource ConvertFileImage}}"  HorizontalAlignment="Left" />
</Grid>