2011-12-18 148 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

相關問題