Add object to ObservableCollection List object

不羁岁月 提交于 2019-12-08 05:45:31

问题


How to add one object to ObservableCollection list object? I have class called "Assest" and I have created ObservableCollection list of Asset and I want to maintain it like adding and deleting element from that ObservableCollection list. Now I'm getting error when I try to add single element to ObservableCollection.

Here's my code.

    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);
    }

So How to over come these kind of situations. Thanks everyone.


回答1:


Your code is a bit messy, it's not clear why you need both AssestList and _collection.

However, I think you need to replace

_collection.Add(ass);

with

AssestList.Add(ass);



回答2:


_collection object still null while you call the getter of AssestList. So, when you use "_collection.Add(ass);", it can be null (and, btw _collection is private, so you can't access it from static function)

To avoid this, use always AssestList.



来源:https://stackoverflow.com/questions/15267585/add-object-to-observablecollection-list-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!