我在Listbox
的ItemTemplate
中使用了一个按钮。有什么方法可以从按钮点击事件中获取Listbox
项的索引?我无法获取按钮的父级。
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Img}">
<Button Click="lstButton_Click">...
我在Listbox
的ItemTemplate
中使用了一个按钮。有什么方法可以从按钮点击事件中获取Listbox
项的索引?我无法获取按钮的父级。
<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);
}
Index
属性,并在将视图模型对象添加到集合时设置它。然后你就可以在事件处理程序中访问它了。private void lstButton_Click(object sender, RoutedEventArgs e)
{
Img t = (sender as Button).DataContext as Img
//Access t.Index here
}