C# 将新项添加到SQLite数据库时更新listview
将数据存储在SQLite数据库中,数据以列表视图的形式显示,当我向数据库添加新条目时,如何使列表视图自动更新,当前必须关闭应用程序并重新打开它以更新信息C# 将新项添加到SQLite数据库时更新listview,c#,sqlite,xaml,uwp,C#,Sqlite,Xaml,Uwp,将数据存储在SQLite数据库中,数据以列表视图的形式显示,当我向数据库添加新条目时,如何使列表视图自动更新,当前必须关闭应用程序并重新打开它以更新信息 public MainPage() { this.InitializeComponent(); TestListViewBinding(); } private void TestListViewBinding() { var db = ne
public MainPage()
{
this.InitializeComponent();
TestListViewBinding();
}
private void TestListViewBinding()
{
var db = new SQLiteConnection(new SQLitePlatformWinRT(), App.path);
var Ingredients = new List<Ingredient>();
{
Ingredients = db.Table<Ingredient>().ToList();
}
TestView.ItemsSource = Ingredients;
}
public主页()
{
this.InitializeComponent();
TestListViewBinding();
}
私有void TestListViewBinding()
{
var db=new SQLiteConnection(new SQLitePlatformWinRT(),App.path);
var components=新列表();
{
成分=db.Table().ToList();
}
TestView.ItemsSource=成分;
}
Xaml
您可以使用来替换列表视图的项目来源的成分列表
ObservableCollection
在添加、删除项目或刷新整个列表时提供通知,例如:
public ObservableCollection<Ingredient> IngredientsCollection = new ObservableCollection<Ingredient>();
private void TestListViewBinding()
{
var db = new SQLiteConnection(new SQLitePlatformWinRT(), App.path);
var Ingredients = new List<Ingredient>();
{
Ingredients = db.Table<Ingredient>().ToList();
}
foreach (var Ingredient in Ingredients)
{
IngredientsCollection.Add(Ingredient); //This is important
}
TestView.ItemsSource = IngredientsCollection;
//TestView.ItemsSource = Ingredients;
}
public observetecollection IngredientsCollection=new observetecollection();
私有void TestListViewBinding()
{
var db=new SQLiteConnection(new SQLitePlatformWinRT(),App.path);
var components=新列表();
{
成分=db.Table().ToList();
}
foreach(成分中的var成分)
{
IngreditsCollection.Add(配料);//这很重要
}
TestView.ItemsSource=IngredientsCollection;
//TestView.ItemsSource=成分;
}
然后,当您将数据添加到数据库中时,不要忘记在将数据添加到此集合后,将数据添加到此“IngredientsCollection”中,列表视图的项将自动添加。获取此错误:不一致的可访问性:字段类型“ObservableCollection”比字段“MainPage”更难访问。IngredientsCollection“您知道我哪里出错了吗?”@matthewfuller,成分
是您的数据模型的名称吗?将绑定的模型和属性设置为公共的。这是数据模型,对吗<代码>类成分{//ID[PrimaryKey][AutoIncrement]public int ID{get;set;}公共字符串IngredientName{get;set;}公共字符串后缀{get;set;}公共字符串IngredientCategory{get;set;}
@matthewfuller,是,尝试在类成分之前添加一个public
。只是一个后续问题,如果listview在一个页面上,而我在另一个页面上添加数据,是否仍然可以从两个页面访问相同的ObservableCollection?
public ObservableCollection<Ingredient> IngredientsCollection = new ObservableCollection<Ingredient>();
private void TestListViewBinding()
{
var db = new SQLiteConnection(new SQLitePlatformWinRT(), App.path);
var Ingredients = new List<Ingredient>();
{
Ingredients = db.Table<Ingredient>().ToList();
}
foreach (var Ingredient in Ingredients)
{
IngredientsCollection.Add(Ingredient); //This is important
}
TestView.ItemsSource = IngredientsCollection;
//TestView.ItemsSource = Ingredients;
}