从按钮单击获取列表框项目索引 [英] Getting Listbox Item Index from Button Click

查看:76
本文介绍了从按钮单击获取列表框项目索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在Listbox ItemTemplateDataTemplate中使用按钮.有什么想法可以从按钮单击中获取Listbox项的索引吗?我看不到抓住按钮的父母.

So I'm using a button in the DataTemplate of my Listbox ItemTemplate. Any ideas how I would grab the index of the item of the Listbox from the button click? I can't see to grab the button's parent.

<ListBox.ItemTemplate>
            <DataTemplate DataType="{x:Type local:Img}">
                <Button Click="lstButton_Click">...

推荐答案

     private void lstButton_Click(object sender, RoutedEventArgs e)
     {
                Button button = sender as Button;           
                int index = _myListBoxName.Items.IndexOf(button.DataContext);
//or try this
                index = _myListBoxName.ItemContainerGenerator.IndexFromContainer(button.DataContext);
     }

这篇关于从按钮单击获取列表框项目索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆