I have a ListView and populate it via DataBinding to a Lists Property in my ViewModel. Additionally, I have a menu for the ListView, with a Delete Command, also bound to my ViewModel. My Problem is now, if I have the ListView initialized, I can delete the lists in it. If I add new lists, I can delete all lists. But then, if I add new items, I can't delete them, because the List I get from the DeleteCommand is the old, already deleted list.
So, after deleting lists, they seem to be somehow, somewhere still present and I can only delete new lists, if the total amount of current lists is higher, than any previous amount of deleted lists.
I hope this is a somehow understandable explanation of my problem.
The Binding is working and Lists Property in my ViewModel holds the correct values, but the "sender" ItemList in the DeleteListCommand is the old ItemList.
Here is my XAML for my ListView:
<ListView x:Name="listView" ItemsSource="{Binding Lists}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="viewCell">
<ViewCell.ContextActions>
<MenuItem Command="{Binding BindingContext.RenameListCommand, Source={x:Reference listView}}" CommandParameter="{Binding .}" Text="Rename" />
<MenuItem Command="{Binding BindingContext.DeleteListCommand, Source={x:Reference listView}}" CommandParameter="{Binding .}" IsDestructive="True" Text="Delete" />
</ViewCell.ContextActions>
<ContentView Margin="0,2,0,2"
HeightRequest="50"
BackgroundColor="{Binding Color}">
<ContentView.GestureRecognizers>
<TapGestureRecognizer BindingContext="{Binding Source={x:Reference listView}, Path=BindingContext}"
Command="{Binding ListTappedCommand}"
CommandParameter="{Binding Source={x:Reference viewCell}, Path=BindingContext}" />
</ContentView.GestureRecognizers>
<ContentView.Content>
<Label Text="{Binding Name}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
TextColor="White"
IsEnabled="True"/>
</ContentView.Content>
</ContentView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And here is my ViewModel:
...
public ObservableCollection<ItemList> lists = new ObservableCollection<ItemList>();
public ObservableCollection<ItemList> Lists
{
get { return lists; }
set
{
lists = value;
OnPropertyChanged("Lists");
}
}
public event PropertyChangedEventHandler PropertyChanged;
...
this.DeleteListCommand = new Command<ItemList>((sender) =>
{
OnDeleteList(sender);
});
...
public ICommand DeleteListCommand { get; set; }
private void OnDeleteList(ItemList itemList)
{
Lists.Remove(itemList);
}
...
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}