WPF How do I find which ListBox item was clicked WPF How do I find which ListBox item was clicked wpf wpf

WPF How do I find which ListBox item was clicked


You should be able to use the DataContext from the clicked Button and get the ListBoxItem container from there, and then select it.

private void LayButton_Click(object sender, RoutedEventArgs e){      Button button = sender as Button;    var dataContext = button.DataContext;    ListBoxItem clickedListBoxItem = ListBoxSelectedMarket.ItemContainerGenerator.ContainerFromItem(dataContext) as ListBoxItem;    clickedListBoxItem.IsSelected = true;}


If you are binding to an object an alternative method could be (in VB)

This then gives you an instance of your object to play with and saves you having any mapping fields on the listbox

Private Sub OTC_Settled_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)        Dim pr_YourObject As New YourObject        Dim btn As Button = CType(sender, Button)        OTC = DirectCast(btn.DataContext, pr_YourObject)     End Sub


I haven't done much WPF programming, but you could try getting the parent of the button if it works the same as a WinForms container object.