Getting Listbox Item Index from Button Click

杀马特。学长 韩版系。学妹 提交于 2020-02-04 07:08:09

问题


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

回答1:


     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);
     }



回答2:


You could add a Index property in your view model and set it when you add the view model object into your collection. And then you can access it in your event handler.

private void lstButton_Click(object sender, RoutedEventArgs e)
    {
        Img t = (sender as Button).DataContext as Img
        //Access t.Index here
    }


来源:https://stackoverflow.com/questions/17057022/getting-listbox-item-index-from-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!