在我的代码后面,我将ListBox的ItemsSource绑定到ObservableCollection,我可以根据需要检索和查看所有项目。
当我尝试向数据库添加新项目时出现问题。除非我再次显式设置ItemsSource,否则视图不会更新,因为绑定数据时,它被绑定到数据库中的旧数据集。
有没有办法可以避免显式设置ItemsSource或明确地将项添加到列表中?
我试图通过插入数据库来实现这一目标!
Code:
//Declarations
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<DBList> itemList = new ObservableCollection<DBList>(dbConn.Table<DBList>().ToList().Where(c1 => c1.ID != null && !c1.value));
public ObservableCollection<DBList> ItemList
{
get{return this.itemList;}
set{this.itemList = value;}
}
//Constructor
DBListBox.ItemsSource = ItemList;
//Method in which I add item to database
private void AddToList(object sender, System.Windows.Input.GestureEventArgs e)
{
InsertToDatabase("abc","xyz"); //Code Inserts a new item in database
//Method 1: The view is updated in this case when I add item to the List
Dispatcher.BeginInvoke(() =>
{
ItemList.Add(new DBList() { Id="abc" , value="xyz"});
NotifyPropertyChanged("ItemList");
});
//Method 2: The view is updated in this case when I explicitly set the ItemsSouce to a fresh list from the Database
DBListBox.ItemsSource = new ObservableCollection<DBList>(dbConn.Table<DBList>().ToList().Where(c1 => c1.ID != null && !c1.value));
}
private void InsertToDatabase(string id, string value)
{
dbConn.CreateTable<DBList>();
DBList cTemp = new DBList(){Id = id, value = value};
dbConn.InsertOrReplace(cTemp);
}