WPF How to find ListBox list item?

I have a WPF application that has a list populated with match elements. How to make a button (contained inside an element) actually select an element so that I can extract the value?

Here is my code: neither works, since pressing a button does not actually select an item

private void LayButton_Click(object sender, RoutedEventArgs e) { var x = (Market)ListBoxSelectedMarket.SelectedItem; var y = (sender as ListBoxItem); } 

thanks

+6
button click wpf listbox listboxitem
source share
3 answers

You can use the DataContext with the button pressed 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; } 
+12
source share

I didn’t program much WPF, but you can try to get the parent of the button if it works the same as the WinForms container object.

0
source share

If you are attached to an object, an alternative method might be (in VB)

Then it gives you an instance of your object for playback and saves you with any display fields in the list

 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 
0
source share

All Articles