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

本文关键字:项目 索引 列表 何获取 获取 | 更新日期: 2023-09-27 18:18:26

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

那么我如何获得一个项目的列表索引,该项目被持有以调出上下文菜单?

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

为什么不访问控件的SelectedIndex属性(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>