Reputation: 12874
i have a listbox with a data template that contains a button.
When the button is clicked I want to get in the button click handler the index of the listbox item that was current??
How do I do this please?
Malcolm
Upvotes: 3
Views: 5443
Reputation: 373
Hi you can use ContentPresenter.Content
to get current item , instead of current index:
<DataTemplate DataType="{x:Type MyModel}">
<StackPanel Orientation="Horizontal" Margin="0 5">
<TextBlock Text="{Binding Title}" />
<Button Content="Active" Click="Button_Click" />
</StackPanel>
</DataTemplate>
and in code:
private void Button_Click(object sender, RoutedEventArgs e)
{
var button = e.Source as Button;
var contentPresenter = button.TemplatedParent as ContentPresenter;
var myModel = (MyModel)contentPresenter.Content;
}
Upvotes: 0
Reputation: 307
Probably way to late but using "IndexOf" on the listbox "Items" will give you the index # Regards
Upvotes: 0
Reputation: 14481
Have you checked the "SelectedIndex" property of the listbox? It might be set by clicking on the button.
Upvotes: 0
Reputation: 50048
More appropriate answer,
private void Button_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is ListViewItem))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
int index = lstBox.ItemContainerGenerator.IndexFromContainer(dep);
}
Upvotes: 5
Reputation: 50048
Hope the bellow code will help you.
private void Button_Click(object sender, RoutedEventArgs e)
{
var b = (Button)sender;
var grid = (Grid)b.TemplatedParent
var lstItem = (ListBoxItem)grid.TemplatedParent;
int index = lstBox.ItemContainerGenerator.IndexFromContainer(lstItem);
// rest of your code here...
}
And the XAML for the above assumed to be a DataTemplate on a ListBox named lstBox
:
<DataTemplate x:Key="template">
<Grid>
<Button Click="Button_Click" Content="Press"/>
</Grid>
</DataTemplate>
Upvotes: 2