Hi all,
I am working in UWP with EntityFrameWorkCore and SQLite.
I am trying to bind to my DbSet, but it doesn't update.
I could make my binding work when I change the property Name, it gets updated. But the ListView doesn't update when I add/remove items to/from my DbSet.
Here is my code:
Here the classes. Note that the binding to DbSet when I add/remove items doesn't work.
But when I modify the name it works and updates.
public class ContactsContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
public class Contact : INotifyPropertyChanged
{
private string _Name;
public event PropertyChangedEventHandler PropertyChanged;
[Key]
public string Name
{
get { return _Name; }
set
{
if (_Name != value)
{
_Name = value;
NotifyPropertyChanged("Name");
}
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
<ListView Name="myListView" ItemsSource="{Binding}"
HorizontalAlignment="Center" VerticalAlignment="Center">
<ListView.ItemTemplate>
<DataTemplate x:DataType="Data:Contact">
<TextBlock Text="{x:Bind Name}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
private void Page_Loaded(object sender, RoutedEventArgs e)
{
using (ContactsContext db = new ContactsContext())
{
myListView.ItemsSource = db.Contacts;
}
}
private void Adder_Click(object sender, RoutedEventArgs e)
{
using (ContactsContext db = new ContactsContext())
{
db.Contacts.Add(new Contact { Name = myTextBox.Text });
db.SaveChanges();
}
}
What I have tried:
I already tried to add the
INotifyPropertyChanged
to my DataContext class, but no effect.
public class ContactsContext : DbContext
{
private DbSet<Contact> _Contacts { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public string Contacts
{
get { return _Contacts; }
set
{
_Contacts = value;
NotifyPropertyChanged("Contacts");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
Tried to create another class that was an ObservableCollection to List the Contacts. But
1) this looked a very complicated solution and I think there must be something easier.
2) it worked fine, but I had some issues when saving the changes (db.SaveChanges).
Someone lived throught this and has some fantastic solution?
thanks.