CounterIt
CounterIt

Reputation: 13

WPF (MVVM) delete item from Listbox

I have created the ViewModel class which return an istance of XmlDataProvider, i bind to it in here in the ListBox, a DeleteCommand (ICommand).

   <ListBox x:Name="Books" Margin="0,0,0,10"    
                     DataContext="{Binding DataProvider}"
                     ItemsSource="{Binding}"                      
                     SelectionMode="Single">
   </ListBox>

 <Button Command="{Binding DeleteCommand}">Remove item</Button>

The listbox load the XML's data and the button execute the DeleteCommand just fine.

My Xml is like this and the DataProvider XPath = "Books/Book":

<Books>
   <Book Id="1">The book</Book>
   ...
</Books>

The problem is i cannot even figure out how to get back the item selected in the list. My goal is to get the id into the ViewModel or bind it to the button and pass it as a paramter but i don't see how.

Anybody can help please?

Upvotes: 0

Views: 1964

Answers (1)

Belterius
Belterius

Reputation: 758

Use the CommandParameter :

<Button Command="{Binding DeleteCommand}" CommandParameter="{Binding ElementName=Books Path=SelectedItem}">Remove item</Button>

This way you will have your SelectedItem passed to your method.

Upvotes: 1

Related Questions