如何将一个对象添加到 ObservableCollection 列表对象?我有一个名为“Assest”的类,我创建了 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);
}
那么如何克服这种情况。谢谢大家。