将数据存储在SQLite数据库中,数据以列表视图显示,当我向数据库添加新条目时,如何让ListView自动更新,当前必须关闭应用程序并重新打开它要更新的信息。
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;
}
的Xaml
<ListView x:Name="TestView" Grid.Row="2" Margin="8,0" ItemsSource="{Binding , Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="auto" HorizontalAlignment="Stretch" >
<TextBlock Grid.Column="0" Text="{Binding IngredientName, Mode=TwoWay}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 0 :(得分:0)
您可以使用ObservableCollection替换Ingredients
ItemsSource
的列表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;
}
然后,当您向数据库添加数据时,不要忘记将数据添加到此“IngredientsCollection”,将数据添加到此集合后,ListView
的项目将自动添加。