pfinferno
pfinferno

Reputation: 1955

Deleting multiple selections in ListBox

I have a ListBox with its SelectionMode property set to Extended to allow for multiple selections inside the ListBox. The ListBox is bound to an ObservableCollection. What I want to do is, when I press the delete key, the selected items in the listbox are removed from the ObservableCollection. I know how to set up the keybinding and use a command for the delete key, but I'm not sure how to get multiple selections from the ListBox.

Here's the listbox:

<ListBox ItemsSource="{Binding XtfPaths}"
         SelectionMode="Extended"/>

Here's the viewmodel:

private ObservableCollection<String> _xtfPaths = new ObservableCollection<String>();
public ObservableCollection<String> XtfPaths
{
    get { return _xtfPaths; }
    set
    {
        if (null != value)
        {
            _xtfPaths = value;
            OnPropertyChanged("XtfPaths");
        }
    }
}

Upvotes: 0

Views: 276

Answers (1)

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

Try this

<Grid>
    <StackPanel>
        <ListBox x:Name="list" Height="200"
        SelectionMode="Extended"
        ItemsSource="{Binding SampleItems}" >
        </ListBox>
        <Button  Content="Remove" Command="{Binding DeleteCommand}"
        CommandParameter="{Binding ElementName=list, Path=SelectedItems}">
        </Button>
    </StackPanel>
</Grid>

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel1();
    }
}

public class MainViewModel1
{
    private ObservableCollection<string> m_items;
    public ObservableCollection<string> SampleItems
    {
        get { return m_items; }
        set { m_items = value; }
    }

    public ICommand DeleteCommand { get; private set; }

    public MainViewModel1()
    {
        DeleteCommand = new RelayCommand<object>(Delete, CanDelete);

        var items = new ObservableCollection<string>();
        var today = DateTime.Now;
        for (int i = 1; i <= 10; i++)
        {
            items.Add("Test"+i);
        }
        SampleItems = items;
    }

    private void Delete(object obj)
    {
        var items = new ObservableCollection<string>();
        foreach (var item in (IList)obj)
        {
            items.Add((string)item);
        }
        foreach (var item in items)
        {
            m_items.Remove(item);
        }
    }

    private bool CanDelete(object obj)
    {
        return true;
    }

}

Upvotes: 1

Related Questions