简体   繁体   English

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

[英]How to get the index of an item in a listbox

If I have a listbox Item , how do I get its index in a list? 如果我有一个listbox Item ,如何在列表中获取其index I have a databound application which lists out data that a user has previously saved. 我有一个数据databound应用程序,该应用程序列出了用户以前保存的数据。 However, I want to be able to delete particular data in the list using a contextMenu . 但是,我希望能够使用contextMenu删除列表中的特定数据。

So how do I get the list index of an item that was held to bring up the context menu? 那么,如何获取为显示上下文菜单而保留的项目的列表索引?

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

However, I want to be able to delete particular data in the list using a ContextMenu. 但是,我希望能够使用ContextMenu删除列表中的特定数据。

You can bind the item directly to the ContextMenu as a CommandParameter , for your delete command. 您可以将项目作为CommandParameter直接绑定到ContextMenu ,以执行删除命令。 This is a much better approach to the problem. 这是解决该问题的更好方法。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM