簡體   English   中英

將新項添加到SQLite數據庫時更新列表視圖

[英]update a listview when a new item is added to SQLite database

將數據存儲在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>

您可以使用ObservableCollection替換ListViewItemsSource的List Ingredients

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項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM