#982 – Executing Code When Selected Items in a ListBox Change

You can handle the SelectionChanged event for a ListBox to react to a change in the currently selected items.

Within the event handler, you can inspect the following properties of the SelectionChangedEventArgs parameter:

  • AddedItems – Collection of items just selected, type matches type of object in collection that ListBox is bound to
  • AddedInfos – Can get index and ListBoxItem for added items
  • RemovedItems – Collection of items just unselected
  • RemovedInfos – Get index and ListBoxItem for removed items
        <ListBox Name="lbActors" Margin="15" Width="200" Height="190"
                 ItemsSource="{Binding ActorList}"
                 SelectionMode="Extended"
                 SelectionChanged="lbActors_SelectionChanged"/>
        <TextBlock Name="tbInfo"/>

 

        private void lbActors_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StringBuilder sbInfo = new StringBuilder();

            sbInfo.AppendLine("Added:");
            foreach (object o in e.AddedItems)
            {
                Actor a = o as Actor;
                sbInfo.AppendLine(a.FullName);
            }

            sbInfo.AppendLine("Removed:");
            foreach (object o in e.RemovedItems)
            {
                Actor a = o as Actor;
                sbInfo.AppendLine(a.FullName);
            }

            tbInfo.Text = sbInfo.ToString();
        }

982-001
982-002
982-003

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: