2011-12-18 67 views
2

如果我有一个listbox Item,如何在列表中获取它的index?我有一个databound应用程序列出了用户以前保存的数据。但是,我希望能够使用contextMenu删除列表中的特定数据。如何获取列表框中某个项目的索引

那么我如何获得一个项目的列表索引来提出上下文菜单?

回答

1

但是,我希望能够使用ContextMenu删除列表中的特定数据。

您可将商品直接绑定到ContextMenu作为CommandParameter,为您删除命令。这是解决问题的更好方法。

<ListBox ItemsSource="{Binding UserItems}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
       <!-- Attach the ContextMenu to the top container in your ItemTemplate. --> 
       <toolkit:ContextMenuService.ContextMenu> 
        <toolkit:ContextMenu> 
         <!-- Here we bind the current item to the RemoveCommand --> 
         <toolkit:MenuItem Command="{Binding RemoveCommand}" 
              CommandParameter="{Binding}" 
              Header="remove item" /> 
        </toolkit:ContextMenu> 
       </toolkit:ContextMenuService.ContextMenu> 
       <!-- The actual DataTemplate --> 
       <TextBlock Text="{Binding SomeValue}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

我明白了。但是,我需要该项目也从用户的内部存储删除,并得到确切的项目,我需要在数组中的索引号。即使我通过这种方式移除屏幕上的项目,我不认为它会影响本地存储 – deztructicus 2011-12-19 11:32:18

+0

如果您绑定了这些项目,您将得到与CommandParameter一样的确切项目。然后,您可以将它从隔离存储中移除,并将ObservableCollection显示到视图中。索引号码不会帮助你。 – 2011-12-19 12:26:36

+0

啊谢谢。我使用哪个函数来删除它?我正在使用 ListBoxItem selectedListBoxItem = this.MainListBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext)as ListBoxItem; 要选择该项目,但如何将其从ObservableCollection中删除? – deztructicus 2011-12-19 15:04:49

相关问题