如何从目录中填充图像列表?

时间:2012-03-26 04:14:44

标签: c# wpf image list

尝试将一堆图像加载到目录中的列表中......我的代码在下面。

        string directory = @".\card_images\";
        List<Image> HandCards = new List<Image>();
foreach (string myFile in 
         Directory.GetFiles(directory,"*.png",SearchOption.AllDirectories))
        {
            HandCards.Add(myFile);
        }

这当然不起作用,因为字符串无法转换为图像,另一方面,如果我尝试将myFile转换为Image然后Directory.GetFiles也不起作用,任何帮助将不胜感激。 谢谢!

4 个答案:

答案 0 :(得分:6)

一个可爱的单线:

var handCards = Directory.GetFiles(directory, "*.png", 
                                   SearchOption.AllDirectories)
                         .Select(Image.FromFile).ToList();

答案 1 :(得分:2)

string directory = @".\card_images\";
List<Image> HandCards = new List<Image>();
foreach (string myFile in
          Directory.GetFiles(directory, "*.png", SearchOption.AllDirectories))
{
    Image image = new Image();
    BitmapImage source = new BitmapImage();
    source.BeginInit();
    source.UriSource = new Uri(myFile, UriKind.Relative);
    source.EndInit();
    image.Source = source;

    HandCards.Add(image);
}

答案 2 :(得分:0)

尝试使用Image.FromFile

例如:

string directory = @".\card_images\";
List<Image> HandCards = new List<Image>();
foreach (string myFile in Directory.GetFiles(directory,"*.png",SearchOption.AllDirectories))
{
    HandCards.Add(Image.FromFile(myFile));
}

答案 3 :(得分:0)

您只需要bind(阅读本文)HandCards集合,并使用ItemTemplate template字符串Image

e.g。

<ItemsControl ItemsSource="{Binding HandCards}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>