从按钮中获取列表框项目索引单击
问题描述:
因此,我在Listbox
ItemTemplate
的DataTemplate
中使用了一个按钮。任何想法如何从按钮点击抓取Listbox
项目的索引?我看不到按钮的父母。从按钮中获取列表框项目索引单击
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Img}">
<Button Click="lstButton_Click">...
答
你可以在你的视图模型添加Index
属性,并设置它,当你添加视图模型对象到您的收藏。然后你可以在你的事件处理程序中访问它。
private void lstButton_Click(object sender, RoutedEventArgs e)
{
Img t = (sender as Button).DataContext as Img
//Access t.Index here
}
答
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);
}
是,当你点击按钮选择的项目? –
不选择索引更改事件不会触发。 – windowskm
您可以使用ICommand而不是ClickEvent,然后您可以将实际Item传递为CommandParameter,或者将Buttons Tag属性设置为Item并从事件处理函数中访问Button Tag属性 –