Remove SelectedItems from a ListBox via MVVM RelayCommand
- by dthrasher
I have a list of items in a WPF ListBox. I want to allow the user to select several of these items and click a Remove button to eliminate these items from the list.
Using the MVVM RealyCommand pattern, I've created a command with the following signature:
public RelayCommand<IList> RemoveTagsCommand { get; private set; }
My ViewModel constructor sets up an instance of the command:
RemoveTagsCommand = new RelayCommand<IList>(RemoveTags, CanRemoveTags);
My current implementation of RemoveTags feels clunky, with casts and copying. Is there a better way to implement this?
public void RemoveTags(IList toRemove)
{
var collection = toRemove.Cast<Tag>();
List<Tag> copy = new List<Tag>(collection);
foreach (Tag tag in copy)
{
Tags.Remove(tag);
}
}