I'm using MVVM architecture in my test project. I have a ListView. The data is bonded to the SQLite database. I want to delete all selected items from the database. The delete button should be activated if at least an item is selected.
I cannot figure out the correct way to delete multiple items.
What is the correct way to delete multiple items from the list and database? Is there any Linq code for this purpose?
What I have tried:
I'm writing only essential parts of my codes:
MainWindow.xaml
<pre lang="C#"><ListView Grid.Row="1" Margin="2" ItemsSource="{Binding PersonList}" SelectedIndex="{Binding SelectedIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectionMode="Extended">
<ListView.View>
<GridView>
<GridViewColumn Header="Row" Width="40" DisplayMemberBinding="{Binding RowNumber}" />
<GridViewColumn Header="Username" Width="100" DisplayMemberBinding="{Binding Username}" />
<GridViewColumn Header="First Name" Width="100" DisplayMemberBinding="{Binding FirstName}" />
<GridViewColumn Header="Last Name" Width="100" DisplayMemberBinding="{Binding LastName}" />
<GridViewColumn Header="Age" Width="40" DisplayMemberBinding="{Binding Age}" />
</GridView>
</ListView.View>
</ListView>
.
.
.
<Button Content="Delete info" Width="100" Command="{Binding DeleteSelectedRow}"/>
RelayCommand:
private Action<object> _action;
private Func<bool> _func;
public RelayCommand(Action<object> action, Func<bool> func)
{
_action = action;
_func = func;
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
}
public bool CanExecute(object parameter)
{
if (_func != null)
{
return _func();
}
else
{
return true;
}
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action(parameter);
}
MainViewModel
private ObservableCollection<Person> _personList;
public ObservableCollection<Person> PersonList
{
get
{
return _personList;
}
set
{
_personList = value;
OnPropertyChanged("PersonList");
}
}
private List<int> _selectedIndex;
public List<int> SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
_selectedIndex = value;
OnPropertyChanged("SelectedIndex");
}
}
public RelayCommand DeleteSelectedRow { get; }
public MainViewModel()
{
.
.
.
DeleteSelectedRow = new RelayCommand((param) => DeleteRow(), () => true);
using (var context = new MyContext())
{
PersonList = new ObservableCollection<Person>(context.Persons);
}
}
private async void DeleteRow()
{
using (MyContext context = new MyContext())
{
List<Person> list = new List<Person>();
for (int i = 0; i < SelectedIndex.Count; i++)
{
list.Add(PersonList[SelectedIndex[i]]);
}
context.Persons.RemoveRange(list);
context.SaveChanges();
PersonList = new ObservableCollection<Person>(context.Persons);
}
}