【问题标题】:How do I add for() loop index identifier to label name?如何将 for() 循环索引标识符添加到标签名称?
【发布时间】:2015-01-27 16:32:54
【问题描述】:

我正在尝试从列表中的对象动态地将内容添加到 WPF 中的标签。 我可以通过硬编码索引号来添加对象中的内容:

// assign forecast values to 5 user interface labels

Forecast fc1 = day.Weather.getForecastInList(0);
day1Label.Content = fc1.Day;
day1ConditionLabel.Content = fc1.ForecastCondition;
day1TempLabel.Content = formatHiLow(fc1.TemperatureHigh, fc1.TemperatureLow);

Forecast fc2 = day.Weather.getForecastInList(1);
day2Label.Content = fc2.Day;
day2ConditionLabel.Content = fc2.ForecastCondition;
day2TempLabel.Content = formatHiLow(fc2.TemperatureHigh, fc2.TemperatureLow);

etc...

但是我将不得不为 5 个标签中的每一个重复很多分配代码。

我尝试使用for() 循环,它可以很好地从列表中获取每个对象,但不会让我重命名标签,例如

// assign forecast values to 5 user interface labels
for (int i = 0; i < 5; i++ )
{
    Forecast fc+(i+1) = day.Weather.getForecastInList(i);
    day+(i+1)+Label.Content = fc+(i+1)+.Day;
}

如何使用for() 循环中的索引动态识别WPF 标签?

【问题讨论】:

  • 删除所有内容并使用ItemsControl。开始阅读here
  • 使用ObservableCollection&lt;ForeCast&gt;ListViewItemsControl等等

标签: c# wpf oop wpf-controls


【解决方案1】:

我不建议这样做,但要回答您的问题,有可能:

创建一个包含所有标签的列表:

List<Label> dayLabels = new List<Label>();
dayLabels.Add(day1Label);
dayLabels.Add(day2Label);
//and so on...

遍历所有标签:

for (int i = 0; i < 5; i++ )
{
    Forecast fc = day.Weather.getForecastInList(i);
    dayLabels.ElementAt(i).Content = fc.Day;
}

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 2012-07-11
    • 2011-08-23
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2021-06-02
    相关资源
    最近更新 更多