试图添加到ObservableCollection但收到错误

时间:2017-04-10 08:50:04

标签: c# list parsing observablecollection

我试图从正在从数据库读入的列表添加到可观察的集合中,但每当我尝试添加它时,它只会抛出错误。我认为这是我添加它的方式,也许我应该在其他地方添加一些内容。 The error I get is 'ChestItems' is a type, which is not valid in the given context

我尝试将项目添加到可观察的集合中,以便它们可以显示在下拉框中。只是名字。

public sealed partial class MainPage : Page
{
    List<Defence> defItems;
    List<HeadItems> headItems;
    ObservableCollection<HeadItems> headList;
    public MainPage()
    {
        headList = new ObservableCollection<HeadItems>();
        headItems = new List<HeadItems>();         
        this.InitializeComponent();
        DataContext = this;
        data();
    }

async void data()
    {
        // items read in from database, parsed and saved in an Object here

        foreach (var item in defItems)
        {

            switch (item.armorType.ToString())
            {
                case "Chest":
                    chestItems.Add(new ChestItems(item.armorName, item.physicalDefence, item.fireDefence, item.magicDefence, item.lightningDefence, item.poise));
                    headList.Add(ChestItems); // this is where the error is 
                    break;
            }
        }
        headDropdown.ItemsSource = headList;
    }
}

3 个答案:

答案 0 :(得分:0)

你有一个错误的说法:

headList.Add(ChestItems);更改为headList.Add(chestItems);

尝试改变这个:

switch (item.armorType.ToString())
{
    case "Chest":
           var  newChestItems=new ChestItems(item.armorName, item.physicalDefence, item.fireDefence, item.magicDefence, item.lightningDefence, item.poise);
        chestItems.Add(newChestItems);
        headList.Add(newChestItems); 
        break;
}

答案 1 :(得分:0)

如果我理解了您要做的事情,请更改

headList.Add(ChestItems); 

headList.Add(chestItems); 

答案 2 :(得分:-1)

这一个:

  

chestItems

正如你的声明

case "Chest":
chestItems.Add(new ChestItems(item.armorName, item.physicalDefence, item.fireDefence, item.magicDefence, item.lightningDefence, item.poise));
 headList.Add(ChestItems); // this is where the error is 
 break;

这个headList必须添加像这样的headItem

headList.Add(headItems)

chestItems不显示任何声明