CounterIt CounterIt - 1 year ago 251
C# Question

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}"

<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":

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download