Frage

The Silverlight version of NotifyCollectionChangedEventArgs differs from the full framework version, in that it does not accept multiple (added, changed, removed) items. The constructors that take lists are in fact missing, so it appears Microsoft intended to block this usage. Indeed, if you pass in a collection of items, they're just nested as the first item of an internal collection.

However! Since the NewItems and OldItems members are of type IList, they are not immutable and can be grown. I made the following helper to test this idea:

    private NotifyCollectionChangedEventArgs CreateEventArgsWithMultiple(NotifyCollectionChangedAction action, IEnumerable items, int newStartingIndex)
    {
        NotifyCollectionChangedEventArgs eventArgs = null;

        foreach (var item in items)
        {
            if (eventArgs == null)
            {
                eventArgs = new NotifyCollectionChangedEventArgs(action, item, newStartingIndex);
            }
            else
            {
                eventArgs.NewItems.Add(item);
            }
        }

        return eventArgs;
    }

I haven't seen any problems yet, but I'm looking for experience and input with this particular corner of Silverlight. Should I bother to batch Adds like this, or just use a Reset?

This is on Windows Phone 7.1 (Mango), by the way.

Edit: To follow up on the comment by Erno. Microsoft says in this (poorly worded) Silverlight documentation page on MSDN that it can be "generally" assumed that NewItems only has one element, and even suggests the shortcut of using NewItems[0] to access it. So they retain the IList signature for "compatibility", but then go on butcher the meaning of the type. Disappointing.

War es hilfreich?

Lösung

I haven't run into any issues, but the answer is "Don't do it!" (unless you're only passing the args to code that you've written).

The reason (as has been said in the comments) is that there may be code in Silverlight which assumes there's only one item. Even if there isn't today, there may be tomorrow, and you definitely don't want your app to break when some new version of Silverlight comes out that relies more heavily on this assumption.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top