向ObservableCollection List对象中添加对象
本文关键字:对象 添加 List ObservableCollection | 更新日期: 2023-09-27 18:02:37
如何添加一个对象到ObservableCollection列表对象?我有一个叫做" Asset "的类,我已经创建了资产的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);
}
那么如何克服这种情况。谢谢所有人。
你的代码有点乱,不清楚为什么你同时需要assets list和_collection。
但是,我认为你需要替换
_collection.Add(ass);
AssestList.Add(ass);
_collection对象仍然是空的,而你调用getter的资产列表。因此,当您使用"_collection. add (ass);"时,它可以为空(而且,_collection是私有的,因此您不能从静态函数访问它)
要避免这种情况,请使用always AssestList.