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