In my viewmodel, I have a list (ObservableCollection) containing items. In the view, this list is displayed in an ItemsControl. In each row, there is a “Delete” button. I want the command behind the button to remove the item from the list.
<ItemsControl ItemsSource="{Binding myList}">
<ItemsControl.ItemTemplate>
...
<Button Command="{StaticResource myDeleteCommand}" CommandParameter="???">
Remove item
</Button>
...
</ItemsControl.ItemTemplate>
</ItemsControl>
What do I pass as the command parameter?
- The item itself (
Binding .)? Then I don’t have a reference to the list in the command, so I’d need to change my model such that each list item contains a back-reference to the list. - The list? Then I don’t have a reference to the item.
- Both? Then I need to write a MultiConverter that translates the list plus the item into some custom object. Seems like a lot of overhead for such a simple task.
Any ideas? This seems like a fairly common scenario to me, so I guess there must be some well-established best-practice solution…
I’ve implemented such commands in that way, that I pass the Item as Parameter. The command self knows on which list it should operate. Either trough a delegate that calls a Delete Method in my ViewModel or the command receives the list of items in it’s constructor.
i.e. a Command with delegates
usage:
EDIT: Forgot XAML