Enlace dinámico de C# XAML a la base de datos durante la operación de la base de datos
Frecuentes
Visto 208 equipos
1
In my code behind I have bound my ListBox's ItemsSource to an ObservableCollection and I am able to retrieve and view all the items as desired.
The problem comes in when I try to add a new item to the database. The view doesnt get updated until unless I explicitly set the ItemsSource again which makes sense since when the data was bound, it was bound to the old data set in the database.
Is there a way I can avoid setting the ItemsSource explicitly or adding an item to the list explicitly?
I am trying to achieve this just by a mere insert into the database!
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);
}
0 Respuestas
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c# sqlite xaml windows-phone-8 or haz tu propia pregunta.
Are you using the wrong NotifyPropertyChanged? Shouldn't call Lista de articulos instead of ChatList? - Smartis
@Smartis I'm sorry it was a typo. It is indeed ItemList that is being called. The two methods above work fine. I am trying a way in which I can avoid doing this. Just an insert into the table must update the view - Rohit Minni
Can you share the code of
InsertToDatabase
? - Dan Puzey@DanPuzey Edited the Question with the
InsertToDatabase
Código Rohit Minni