【问题标题】:C# - how to add images from folder to array and display them in listview?C# - 如何将图像从文件夹添加到数组并在列表视图中显示?
【发布时间】:2017-03-31 21:14:52
【问题描述】:
string[] list = Directory.GetFiles(@"Resources/", "*.jpg");
lvDataBinding.Items.Add(list[0]);

因此文件夹 Resources 包含我想要添加到数组中的几个图像,以便我可以更轻松地使用它们。

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

我想知道我是否也可以将它们与 ListViewItem 名称和描述一起存储在一个类中。所以我可以这样做:

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

然后我猜类会是这样的吗?

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.:我尊重所有关于如何以另一种更好的方式做到这一点的建议。我相信有更好的方法,但我正在做大学作业,而且我的时间有限,我的老师也建议将对象“转移”到新窗口中。 提前致谢!

【问题讨论】:

  • 创建一个带有ICollection 属性的ViewModel,并将此属性用作ItemsSource 用于您的ListBox
  • 你能说得更详细些吗?我不太明白。另外,我有 ListView 而不是 ListBox。
  • 答案是肯定的,你可以这样做。但是,您必须更具体地回答您的问题。我不认为一个简单的“是”回答对你有多大帮助。

标签: c# wpf image


【解决方案1】:

您可以使用string 属性存储图像的路径。请参考以下示例代码。

代码:

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" />

【讨论】:

  • 非常感谢。如果我有 .jpg 和 .png ,我将如何更改路径数组?另外我该如何选择要设置的路径?我假设在“Path = path”行中它会类似于“Path = picture.png”?
  • 我不确定我是否理解。每个 Image 都有一个完整路径,用于指定文件的目录和名称。
  • 举个例子,我将如何在上面的代码中使用图片“asus.jpg”。我应该把它放在哪里。
  • 像以前一样把“.png”改成“.jpg”,放到Resouces文件夹里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多