Remove SelectedItems from a ListBox via MVVM RelayCommand

Posted by dthrasher on Stack Overflow See other posts from Stack Overflow or by dthrasher
Published on 2010-05-10T14:59:58Z Indexed on 2010/05/10 15:04 UTC
Read the original article Hit count: 1145

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about wpf

Related posts about mvvm