MVVM WPF удаление нескольких выбранных элементов

449
27 мая 2017, 15:20

Есть ListBoxсо списком автомобилей

<ListBox x:Name="autoList" Grid.Column="0" ItemsSource="{Binding Auto}"  
         SelectedItem="{Binding SelectedAuto}">

Есть коллекция, в которой находятся данные из БД ObservableCollection<Auto> Auto;

как сделать удаление нескольких выделенных в ListBox автомобилей? для удаления 1 авто использую следующий код

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; }
}

ViewModel

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}"  />

код VM

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));
    }
Answer 1

У меня работает такой способ, разметка:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListBox Name="ListBox"
             ItemsSource="{Binding Autos}" DisplayMemberPath="Model"
             SelectionMode="Extended" Margin="5,5,5,0"/>
    <Button Grid.Row="1" Content="Delete" Margin="5"
            Command="{Binding DeleteCommand}"
            CommandParameter="{Binding SelectedItems, ElementName=ListBox}"/>
</Grid>

В коде VM:

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));
}

READ ALSO
Просмотр интернет видео в программе

Просмотр интернет видео в программе

Стало интересно, возможно ли сделать плеер который будет отображать фильмы с различных сайтов в виде каталога и при воспроизведении будет...

343
Что внутри функции lerp

Что внутри функции lerp

в Unity 3d есть метод Vector3Lerp

287
Самодельный UIElement WPF c событием

Самодельный UIElement WPF c событием

ЗдравствуйтеХочу создать UIElement, содержащий, например, 2 стандартных эллипса:

423
Tls сервер/клиент

Tls сервер/клиент

Никак не получается соединить даже 2 примера с msdn: https://msdnmicrosoft

399