【问题标题】:getting file in while loop by his name用他的名字在while循环中获取文件
【发布时间】:2017-03-24 21:16:42
【问题描述】:

我有一个while循环:

int a = 0;

while (list_Level[a] < Initial_Lvl)
{
    var dOpt = new DataGridObjectOpt();
    dOpt.ImageSource = new Uri(filePaths[a], UriKind.RelativeOrAbsolute);

    a++;
}

通过这种方式,我从filePaths 的文件夹中获取图像,但我无法控制它们的顺序,除非我更改它们的名称。

我想要下一个 while 循环,例如:(我有 3 张名为“apple.jpg”、“orange.jpg”、“banana.jpg”的图像)

int a = 0;
string[] name = ['apple','orange','banana']
while (a < 2)
{
    var dOpt = new DataGridObjectOpt();
    dOpt.ImageSource = new Uri(string.Format("{0}.jpg", name[a]); UriKind.RelativeOrAbsolute);

    a++;
}

但我仍然希望它像以前一样在文件路径中搜索这些图像。

谢谢。

【问题讨论】:

  • 什么? LOpt_Temp 是什么?它似乎与您发布的其余代码完全无关。此外,您的第二个 sn-p 有几个问题会阻止它编译。我不知道你想做什么。
  • 我有几个列表,最终我将它们ItemSource 到一个dataGrid 中。将成为 dataGrid 中的列的列表之一由图像组成。我只想专注于我的问题中的这个专栏,所以我发布了它。

标签: c# arrays image list uri


【解决方案1】:

你必须用双引号定义的字符串来初始化你的字符串数组,并且你需要用大括号替换那些方括号:

string[] name = {"apple", "orange", "banana"};

您还需要将ImageSource 赋值中的分号替换为逗号:

dOpt.ImageSource = new Uri(string.Format("{0}.jpg", name[a]), UriKind.RelativeOrAbsolute);

最后,您在 while 语句中声明了您的 DataGridObjectOpt 对象,因此它们仅在您处于循环中时存在,这意味着您的代码实际上并没有做任何事情。

当我们无法判断您真正想要做什么时,几乎不可能给您答案。你对这些dOpt 对象有什么计划???

这是我对您解决方案的最佳猜测。它从您定义的filePathname 列表中创建Uri 对象列表。然后您可以稍后使用它来分配您的 DataGridObjectOpt 对象 ImageSource 属性:

var imageSourceUris = new List<Uri>();

for (int i = 0; i < Initial_Lvl; i++)
{
    imageSourceUris.Add(new Uri(filePaths[i], UriKind.RelativeOrAbsolute));
}

string[] names = {"apple", "orange", "banana"};

foreach (var name in names)
{
    imageSourceUris.Add(new Uri($"{name}.jpg", UriKind.RelativeOrAbsolute));
}

// Now you have a list of Uris that you can assign to
// different DataGridObjectOpt object ListSource properties
// This example just creates a bunch of them and assigns the property

var dataGridOptions = new List<DataGridObjectOpt>();

foreach (var imageSourceUri in imageSourceUris)
{
    dataGridOptions.Add(new DataGridObjectOpt {ImageSource = imageSourceUri});
}

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2021-06-22
    • 2014-06-20
    相关资源
    最近更新 更多