Archive for the 'wpf' Category

Getting the selected (or de-selected) ListBoxItems in WPF

Getting the ListBoxItem during a selection event used to be much easier in standard winforms. In the new SelectionChanged event in WPF, you don’t get the ListBoxItem that generated the selection event, you get back the data item that was used to bind to that ListBoxItem. So how do you get the ListBoxItem? It’s actually not so hard, you just have to ask the ItemContainerGenerator to give it to you. For example:


void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = (ListBox) sender;

// handle selected items
foreach (MyClass datum in e.AddedItems)
{
ListBoxItem listBoxItem = (ListBoxItem) listBox.ItemContainerGenerator.ContainerFromItem(datum);
// do something with the listBoxItem
}

// handle deselected items
foreach (MyClass datum in e.RemovedItems)
{
ListBoxItem listBoxItem = (ListBoxItem) listBox.ItemContainerGenerator.ContainerFromItem(datum);
// sometimes this can be null
if (listBoxItem == null)
break;

// do something with the listBoxItem
}
}