Getting Listbox Item Index from Button Click
Asked Answered
W

2

3

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">...
Warnerwarning answered 12/6, 2013 at 2:59 Comment(3)
Is the Item selected when you click the button?Presence
Nope the selected index changed event doesn't trigger.Warnerwarning
You could use an ICommand instead of ClickEvent, then you could pass the actual Item as the CommandParameter, or set the Buttons Tag property to the Item and access the Button Tag property from the event handlerPresence
M
12
     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);
     }
Mathia answered 23/1, 2014 at 9:41 Comment(0)
S
0

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
    }
Sicilia answered 12/6, 2013 at 6:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.