locked
ItemsSource changed event? RRS feed

  • Question

  • Hello,

    I need to add an event to my ListBox when it's ItemsSource has changed, is this possible?

    Thanks!

    Friday, June 12, 2009 3:36 PM

Answers

  • Hi,

    Create a usercontrol that inherits from the ListBox control.  Create the event handler.  Add the new listbox and subscribe to the new event handler.

    New control:

    1        public partial class myListBox : ListBox
    2        {
    3            public delegate void ItemsSourceChangedHandler(object sender, EventArgs e);
    4    
    5            public event ItemsSourceChangedHandler ItemsSourceEvent;
    6    
    7            public new System.Collections.IEnumerable ItemsSource
    8            {
    9                get { return base.ItemsSource; }
    10               set
    11               {
    12                   base.ItemsSource = value; 
    13                   EventArgs e = new EventArgs();
    14                   OnItemsSourceChanged(e);
    15               }
    16           }
    17   
    18           protected virtual void OnItemsSourceChanged(EventArgs e)
    19           {
    20               if (ItemsSourceEvent != null)
    21                   ItemsSourceEvent(this, e);
    22           }
    23       }
    

    Add reference to your control in your xaml file:

    xmlns:myControls="clr-namespace:yourProjectName"

     Add an instance of your control:

    <myControls:myListBox x:Name="myList" Width="100" Height="400" ItemsSourceEvent="myList_ItemsSourceEvent"></myControls:myListBox>

     Add event handler

    void myList_ItemsSourceEvent(object sender, EventArgs e)
    {

    MessageBox.Show("Items Source changed.");
    }

     

    Saturday, June 13, 2009 7:41 PM