Professional, Software

OnItemsChanged

ItemsControl class in Silverlight Beta2 has added  protected virtual method OnItemsChanged. This method is invoked when Items Property changes. This could be used to add a custom behavior when items are added or removed. Here is the quick sample.

I wanted Listbox where when a selected item is removed, it selects the next item in the list.

CustomListBox

 

   1: public class MyListBox: ListBox
   2:     {
   3:         protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   4:         {
   5:             base.OnItemsChanged(e);
   6:             if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
   7:             {
   8:                 if (e.OldStartingIndex < Items.Count)
   9:                     SelectedItem = Items[e.OldStartingIndex];
  10:                 else
  11:                     SelectedItem = Items[Items.Count - 1];
  12:             }
  13:         }
  14:     }

Here is the sample that compares the behavior of default listbox and customlist box.

Advertisements
Standard

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