将新项添加到SQLite数据库时更新列表视图

时间:2016-07-20 23:17:01

标签: c# sqlite xaml uwp

将数据存储在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>

1 个答案:

答案 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的项目将自动添加。