WPF Tip: Collection Changed Event


Hi, quick tip for WPF. I’m set to leave for my 2 week vacation today, so this will be a quick one.

I was building a physics simulation in WPF (still to be completed), and as usual I binded my ObservableCollection to a Custom Canvas control, which I specified in my ItemsControl‘s ItemPanelTemplate. If you have noticed, all the WPF “container” controls like ListBox, ItemsControl, etc all have an ItemsSource propery where you can specify your data source. So what happens when I add/remove something from that data source, how do I get notified???

I did some digging around, but realised there’s no such event that gets triggered. The trick is to look at the the Items property, which is of type System.Windows.Controls.ItemCollection. It inherits from a CollectionView, which implements the INotifyCollectionChanged interface, which has the CollectionChanged event. Bingo, here we go…

This is sample code that demonstrates how to use this.

public Window1()
{
    InitializeComponent();
    particles.Add(CreateParticle());
    ((INotifyCollectionChanged)itemsControl.Items).CollectionChanged += new NotifyCollectionChangedEventHandler(Window1_CollectionChanged);
    itemsControl.ItemsSource = particles;
}

void Window1_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        // do something
    }
}

So you will now be notified of changes in your control’s Items due to changes in your data source. You might also want to learn more about the NotifyCollectionChangedEventArgs, it has some useful properties in there. Also you should have a look at NotifyCollectionChangeAction enum values to learn more about what kind of notification actions are available.

Share this post :
Advertisements
Posted in WPF. Tags: . 3 Comments »

3 Responses to “WPF Tip: Collection Changed Event”

  1. Martin Says:

    Thanks! This helped me alot!

    Kind regards,
    Martin

  2. How to listen to CollectionChanged event and execute some method | Zart Answers Says:

    […] can allow to MainCollection.CollectionChanged and refresh subsequent collection […]

  3. pracsmadeasy Says:

    Awesome!!!! This is the best and easiest solution I have every found on the net!!!!


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: