Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 247
Chris Avatar asked Jan 20 '11 23:01

Chris


1 Answers

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;
}
like image 133
Fredrik Hedblad Avatar answered Sep 17 '22 17:09

Fredrik Hedblad