将对象添加到ObservableCollection List对象

时间:2013-03-07 09:35:16

标签: c# wpf list observablecollection

如何将一个对象添加到ObservableCollection列表对象?我有一个名为“Assest”的类,我创建了ObservableCollection资产列表,我想维护它,就像在ObservableCollection列表中添加和删除元素一样。现在,当我尝试将单个元素添加到ObservableCollection时,我遇到了错误。

这是我的代码。

    private static ObservableCollection<Assest> _collection = null;

    public ObservableCollection<Assest> AssestList
    {
        get
        {
            if (_collection == null)
            {
                _collection = new ObservableCollection<Assest>();
            }
            return _collection;
        }
        set { _collection = value; }
    }

    public static ObservableCollection<Assest> ToObservableCollection(List<Assest> assestList)
    {
        return new ObservableCollection<Assest>(assestList);
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        LoadData();
        comboBox1.ItemsSource = AssestList;
    }

    private void LoadData()
    {
        Assest assest = new Assest() { AppID = "1", AssestName = "AppName", AppDescription = "Description" };
        Assest assest2 = new Assest { AppDescription = "Des2", AppID = "2", AssestName = "hi" };

        List<Assest> assList = new List<Assest> {assest, assest2};

        ObservableCollection<Assest> generatedAssestList = ToObservableCollection(assList);
        AssestList = generatedAssestList;
    }

    // Here I get an error.

    public static void AddAppToObservalCollection(Assest ass)
    {
        _collection.Add(ass);
    }

那么如何应对这种情况呢?谢谢大家。

2 个答案:

答案 0 :(得分:3)

您的代码有点乱,不清楚为什么需要AssestList和_collection。

但是,我认为你需要更换

_collection.Add(ass);

AssestList.Add(ass);

答案 1 :(得分:1)

调用AssestList的getter时,

_collection对象仍然为null。因此,当您使用“_collection.Add(ass);”时,它可以为null(并且,btw _collection是私有的,因此您无法从静态函数访问它)

要避免这种情况,请始终使用AssestList。