如果我有一個listbox Item
,如何在列表中獲取它的index
?我有一個databound
應用程序列出了用戶以前保存的數據。但是,我希望能夠使用contextMenu
刪除列表中的特定數據。如何獲取列表框中某個項目的索引
那麼我如何獲得一個項目的列表索引來提出上下文菜單?
如果我有一個listbox Item
,如何在列表中獲取它的index
?我有一個databound
應用程序列出了用戶以前保存的數據。但是,我希望能夠使用contextMenu
刪除列表中的特定數據。如何獲取列表框中某個項目的索引
那麼我如何獲得一個項目的列表索引來提出上下文菜單?
爲什麼不訪問該控件的SelectedIndex property(MSDN)?
但是,我希望能夠使用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>
我明白了。但是,我需要該項目也從用戶的內部存儲刪除,並得到確切的項目,我需要在數組中的索引號。即使我通過這種方式移除屏幕上的項目,我不認爲它會影響本地存儲 – deztructicus 2011-12-19 11:32:18
如果您綁定了這些項目,您將得到與CommandParameter一樣的確切項目。然後,您可以將它從隔離存儲中移除,並將ObservableCollection顯示到視圖中。索引號碼不會幫助你。 – 2011-12-19 12:26:36
啊謝謝。我使用哪個函數來刪除它?我正在使用 ListBoxItem selectedListBoxItem = this.MainListBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext)as ListBoxItem; 要選擇該項目,但如何將其從ObservableCollection中刪除? – deztructicus 2011-12-19 15:04:49