Firstly, I would process the command in ViewModel. I assume that the list that is used for binding is in the ViewModel, so any code that "works" in this list should also be executed in the ViewModel.
class MyViewModel { // ... Clipping rest of ViewModel class ... private ObservableCollection<MyObject> mMyList = new ObservableCollection<MyObject>(); private ICommand mMyDeleteCommand; public MyViewModel() { InitializeMyListSomehow(); mMyDeleteCommand = new MyCommandClass( (item) => DeleteItem(item), () => mDeleteCanExecute ); } public ObservableCollection<MyObject> MyList { get { return mMyList; } set { // Some function that updates the value and implements INPC SetProperty("MyList", ref mMyList, value); } } public ICommand MyDeleteCommand { get { return mMyDeleteCommand; } } void DeleteHandler(var item) { int index = mMyList.Remove(item); } }
Are the items unique? If so, you can pass the item, and the Delete command handler can find the item in the list.
If the elements are not unique, you will need to do a little more logic, depending on the expected result.
Now, in the view, your code will look (note that StaticResource becomes a binding):
<ItemsControl ItemsSource="{Binding MyList}"> <ItemsControl.ItemTemplate> ... <Button Command="{Binding DataContext.MyDeleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}"> Remove item </Button> ... </ItemsControl.ItemTemplate> </ItemsControl>
source share