如何获取列表框中项目的索引

时间:2011-12-18 22:35:06

标签: c# windows-phone-7

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

那么如何获取为调出上下文菜单而保留的项目的列表索引?

2 个答案:

答案 0 :(得分:5)

为什么不访问控件的SelectedIndex property(MSDN)?

答案 1 :(得分: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>