Home > Blockchain >  Calling method on SelectionChanged ListBox event with the selected item as parameter
Calling method on SelectionChanged ListBox event with the selected item as parameter

Time:04-28

I'm trying to call a method which fills a table with data according to the ListBoxItem that has been selected.

// Setting the ListBoxItems
myListBox.ItemsSource = list;
// Calling the method when the ListBox's selection changes
myListBox.SelectionChanged  = LbItem_Select;

The above snippet can't work because the LbItem_Select event handler doesn't get as a parameter the item that is currently selected.

This is the event handler:

private void LbItem_Select(object sender, RoutedEventArgs e)
{
    var lbItem = sender as ListBoxItem;
    lbItemContent = lbitem.Content.ToString();
    // fill the table according to the value of lbItemContent
}

How could I achieve this?

CodePudding user response:

When you work with events, sender is the object related to the event. myListBox.SelectionChanged is an event of the ListBox. So sender is the ListBox, not the item. Try with this:

private void LbItem_Select(object sender, RoutedEventArgs e)
{
    var listBox = sender as ListBox;
    // Or use myListBox directly if you have the ListBox available here
    
    var item = listBox.SelectedItem;
    // Do whatever with the item
}
  • Related