是ListBox的,有汽车清单
<ListBox x:Name="autoList" Grid.Column="0" ItemsSource="{Binding Auto}"
SelectedItem="{Binding SelectedAuto}">
我有一个包含数据库中数据的集合ObservableCollection<Auto> Auto;
如何删除列表框中选中的多辆汽车?删除 1 auto 使用以下代码
public RelayCommand DeleteCommand
{
get
{
return deleteCommand ??
(deleteCommand = new RelayCommand((selectedItem) =>
{
MessageBoxResult result = MessageBox.Show("Вы действительно желаете удалить элемент?", "Удаление", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (selectedAuto == null || result == MessageBoxResult.No) return;
// получаем выделенный объект
Auto auto = selectedAuto as Auto;
db.Autos.Remove(auto);
db.SaveChanges();
OnPropertyChanged("HasAuto");
}, CanEditOrDeleteAuto));
}
}
该类Auto看起来像这样(数据库表看起来一样)
class Auto : INotifyPropertyChanged
{
private string model;
private string marka;
private int cost;
private int maxSpeed;
public int Id { get; set; }
public string Model
{
get
{
return model;
}
set
{
model = value;
OnPropertyChanged("Model");
}
}
public string Marka
{
get
{
return marka;
}
set
{
marka = value;
OnPropertyChanged("Marka");
}
}
public int Cost
{
get
{
return cost;
}
set
{
cost = value;
OnPropertyChanged("Cost");
}
}
public int MaxSpeed
{
get
{
return maxSpeed;
}
set
{
maxSpeed = value;
OnPropertyChanged("MaxSpeed");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
我得到这样的数据库
public class ApplicationContext : DbContext
{
public ApplicationContext() : base("DefaultConnection")
{
}
public DbSet<Auto> Autos { get; set; }
}
视图模型
ObservableCollection<Auto> autos;
private Auto selectedAuto;
public ObservableCollection<Auto> Autos
{
get { return autos; }
set
{
autos = value;
OnPropertyChanged("Autos");
}
}
public Auto SelectedAuto
{
get
{
return selectedAuto;
}
set
{
selectedAuto = value;
OnPropertyChanged("SelectedAuto");
}
}
public ApplicationViewModel()
{
db = new ApplicationContext();
db.Autos.Load();
Autos = db.Autos.Local;
}
UDP2 标记
<Button Content="Удалить" Margin="10" Command="{Binding DeleteCommand}" Style="{StaticResource InformButton}"
CommandParameter="{Binding SelectedItems, ElementName=autoList}" />
虚拟机代码
public ICommand DeleteCommand => new RelayCommand(o => Delete((Collection<object>)o));
private void Delete(Collection<object> o)
{
List<Auto> list = o.Select(e => (Auto)e).ToList();
list.ForEach(auto => Autos.Remove(auto));
}
这种方式对我有用,标记:
在虚拟机代码中: