简体   繁体   English

WPF(MVVM)从列表框中删除项目

[英]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). 我创建了ViewModel类,该类返回了XmlDataProvider的一个距离,我在这里将其绑定到ListBox中的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. 列表框加载XML的数据,按钮执行DeleteCommand就好了。

My Xml is like this and the DataProvider XPath = "Books/Book": 我的Xml就是这样,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. 我的目标是将ID放入ViewModel或将其绑定到按钮,并将其作为参数传递,但是我不知道如何。

Anybody can help please? 有人可以帮忙吗?

Use the CommandParameter : 使用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. 这样,您便可以将SelectedItem传递到您的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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