Desperately Seeking Love of Sophie

OnItemsChanged

leave a comment »

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.

Written by Vivek

June 10, 2008 at 6:17 am

Leave a Reply