Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

wpf - C# - how to add images from folder to array and display them in listview?

string[] list = Directory.GetFiles(@"Resources/", "*.jpg");
lvDataBinding.Items.Add(list[0]);

So the folder Resources contains several images that I want to add to an array so I can use them in an easier way.

I need to display them in a window (each one when a different listviewitem is selected).

I would like to know if I can also store them in a class alongside the ListViewItem name and description. So I can do like:

Article article1= new Article();
article1.Name = "Article name";
article1.Description = "Long article description etc etc";
article1.Image= images[0];
lvDataBinding.Items.Add(artikel1);

And then class would be something like this I guess?

public class Article
{
    public string Name{ get; set; }
    public string Description{ get; set; }
    public Image? Image { get; set; }

    public override string ToString()
    {
        return Naziv;
    }
}

P.S.: I respect all suggestions on how I could do this on another better way. Im sure there are better ways, but I am doing a college assignment and I'm limited on time, also my teacher suggested to "transfer" objects into new windows. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could store the path of the image using string property. Please refer to the following sample code.

Code:

public class Article
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }
}
...
string[] list = Directory.GetFiles(@"Resources/", "*.png");
List<Article> items = new List<Article>();
foreach (var path in list)
{
    items.Add(new Article()
    {
        Name = System.IO.Path.GetFileNameWithoutExtension(path),
        Path = path
    });
}
lvDataBinding.ItemsSource = items;

XAML:

<ListView x:Name="lvDataBinding" DisplayMemberPath="Name" />
<Image Source="{Binding SelectedItem.Path, ElementName=lvDataBinding}" Stretch="None" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...