简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM