Chris
Chris

Reputation: 1207

WPF How do I find which ListBox item was clicked

I have a WPF application in which there's a listbox filled with items of type 'Match'. How do I make the button(contained within the item) actually select the item so that I might extract the value?

Here is my code: neither works since clicking the button doesn't actually select the item

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

}

Thanks

Upvotes: 7

Views: 5039

Answers (3)

Chris Allison
Chris Allison

Reputation: 73

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

Upvotes: 0

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84657

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;
}

Upvotes: 12

jamiegs
jamiegs

Reputation: 1791

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.

Upvotes: -2

Related Questions