Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - How do determine the index of the current item in a listbox from button handler

Tags:

c#

.net

wpf

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

like image 673
Malcolm Avatar asked Nov 25 '25 10:11

Malcolm


1 Answers

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>
like image 86
Jobi Joy Avatar answered Nov 28 '25 00:11

Jobi Joy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!