Getting Listbox Item Index from Button Click

2019-07-24 02:03发布

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

2条回答
叛逆
2楼-- · 2019-07-24 02:45
     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);
     }
查看更多
虎瘦雄心在
3楼-- · 2019-07-24 02:59

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
    }
查看更多
登录 后发表回答