正在从ObservableCollection中删除项

本文关键字:删除 ObservableCollection | 更新日期: 2023-09-27 17:59:03

我有一个列表视图,它绑定到ObservableCollection,我正在尝试使用它,这样当按下按钮时,该项目就会从列表和SQLite数据库中删除,到目前为止,它只从数据库中删除。除非我重新启动应用程序,否则该项目在ListView中不再存在,有人能告诉我我做错了什么吗?

代码背后:

namespace Epicure.Views
{
public sealed partial class Ingredients : Page
{
    public Ingredients()
    {
        this.InitializeComponent();
        TestViewBinding();
        this.DataContext = this;
    }
    public static ObservableCollection<Ingredient> IngredientsCollection = new ObservableCollection<Ingredient>();
    public void TestViewBinding()
    {
        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);
        }
    }
    private void ListUpdated(object sender, object e)
    {
        if (IngredientsCollection.Count == 0)
        {
            LonelyPanel.Visibility = Visibility.Visible;
        }
        if (IngredientsCollection.Count > 0)
        {
            LonelyPanel.Visibility = Visibility.Collapsed;
        }
    }
    private void RemoveClicked(object sender, RoutedEventArgs e)
    {
        var db = new SQLiteConnection(new SQLitePlatformWinRT(), App.path);
        var Ingredients = db.Table<Ingredient>().ToList();
        foreach (var Ingredient in Ingredients)
        {
            db.Delete(Ingredient);
            IngredientsCollection.Remove(Ingredient);
        }          
    }
    private void NewIngredientClicked(object sender, RoutedEventArgs e)
    {
        NavigationService.NavigateToPage(typeof(NewIngredient));
    }
}

}

XAML:

<Page
x:Class="Epicure.Views.Ingredients"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Epicure.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <ListView x:Name="IngredientList" ItemsSource="{Binding IngredientsCollection}" SelectionMode="Single" BorderThickness="0,1,0.5,0" BorderBrush="#FF007575" LayoutUpdated="ListUpdated">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Height="140" HorizontalAlignment="Stretch">
                    <StackPanel>
                    <TextBlock Text="{Binding IngredientName}"/>
                        <AppBarButton x:Name="DeleteButton" Style="{StaticResource EpicureRibbonButton}" Width="48" Click="RemoveClicked" Icon="Delete"/>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <StackPanel x:Name="LonelyPanel" VerticalAlignment="Center" HorizontalAlignment="Center">
        <TextBlock x:Name="Icon" TextWrapping="Wrap" TextAlignment="Center" Text="&#xED56;" FontFamily="Segoe MDL2 Assets" FontSize="48" Margin="0" Foreground="#FF007575"/>
        <TextBlock x:Name="Text" TextWrapping="Wrap" TextAlignment="Center" Margin="0,12,0,0" Foreground="#FF007575">
            <Run Text="It's lonely here,"/>
            <LineBreak/>
            <Run Text="want to add something?"/>
        </TextBlock>
        <AppBarButton x:Name="AddIngredient" HorizontalAlignment="Stretch" Label="Add Ingredient" VerticalAlignment="Stretch" Style="{StaticResource AddButton}" Width="Auto" Margin="0,12,0,0" Foreground="#FF007575" Click="NewIngredientClicked">
            <AppBarButton.Icon>
                <FontIcon Glyph="&#xEC09;" FontSize="20"/>
            </AppBarButton.Icon>
        </AppBarButton>
    </StackPanel>
</Grid>

正在从ObservableCollection中删除项

我认为要修改observalecollection,您应该对集合的副本进行迭代。

在应该比较属性(最好是id)的地方,可以这样尝试。

var copy = new ObservableCollection<Ingredient>(IngredientsCollection);
copy.Remove(copy.Where(i => i.Id == Ingredient.Id).Single());

根据最新的代码示例,看起来您实际上并没有绑定ItemSource,而是从可能导致问题的代码中分配它。

首先更新XAML以将ItemsSource正确绑定到ObservableCollection

<ListView x:Name="IngredientList" ItemsSource="{Binding IngredientsCollection}" SelectionMode="Single" BorderThickness="0,1,0.5,0" BorderBrush="#FF007575" LayoutUpdated="ListUpdated">

TestListViewBinding方法中删除IngredientList.ItemsSource = IngredientsCollection;,因为这将由绑定处理

确保视图的DataContext设置为声明集合的类。由于它似乎是你的代码,你可以在构造函数中设置它

public Ingredients()
{
    this.InitializeComponent();
    this.DataContext = this;
    IngredientsCollection = new ObservableCollection<Ingredient>()
    TestViewBinding();
};

请确保您的IngredientsCollection是属性,而不是字段。

public ObservableCollection<Ingredient> IngredientsCollection { get; set; }

因为您的Page没有实现INotifyPropertyChanged,所以IngredientsCollection需要在构造函数中初始化,以便绑定到.

显然,这不是设置MVVM的理想方式,但这是一个开始。