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 RelayCommand pattern, I've created a command with the following signature:
public RelayCommand<IList> RemoveTagsCommand { get; private set; }
In my View, I wire up my RemoveTagsCommand like this:
<DockPanel>
<Button DockPanel.Dock="Right" Command="{Binding RemoveTagsCommand}" CommandParameter="{Binding ElementName=TagList, Path=SelectedItems}">Remove tags</Button>
<ListBox x:Name="TagList" ItemsSource="{Binding Tags}" SelectionMode="Extended">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Resources>
<DataTemplate DataType="{x:Type Model:Tag}">
...
</DataTemplate>
</ListBox.Resources>
</ListBox>
</DockPanel>
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);
}
}