tags:

views:

44

answers:

1

this is in regards to the tutorial on msdn. This is whats used to close workspaces or tabs.

// workspaces declared as follows
_workspaces = new ObservableCollection<WorkspaceViewModel>();
_workspaces.CollectionChanged += this.OnWorkspacesChanged;

void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null && e.NewItems.Count != 0)
        foreach (WorkspaceViewModel workspace in e.NewItems)
            workspace.RequestClose += this.OnWorkspaceRequestClose;

    if (e.OldItems != null && e.OldItems.Count != 0)
        foreach (WorkspaceViewModel workspace in e.OldItems)
            workspace.RequestClose -= this.OnWorkspaceRequestClose;
}

What i don't understand is what will e.NewItems and e.OldItems be. Assuming NewItems will be the new item thats added into the collection, I attach the event handler? But then it will be singular, since I add 1 item at a time usually? then if it means all the items that will still exists after the change, why will I need to re-attach the event handlers?

A: 

Hi,

The method is for handling a NotifyCollectionChanged event - it can be for an 'Add', 'Move', 'Remove', 'Replace' or 'Reset' action. ie items are being added or removed (etc) to/from the collection.

  • NewItems is the list of the new items invoved in the change.
  • OldItems is the list of items affected by a Replace, Remove, or Move action.

So in other words, when you add a ViewModel into the collection, the 'OnWorkspaceRequestClose' handler gets attached to the 'RequestClose' event of just that new ViewModel.

If you add another ViewModel(s), then the handler gets attached to the new one(s), but the existing items in the collection won't be affected...

Incidentally, the second half of the method is removing the OnWorkspaceRequestClose event handlers for those ViewModels being closed (to prevent memory leaks)

IanR