views:

46

answers:

3

I have a public property called Items, It's a List. I want to tell when it's been altered. How can I do this?

For example, if Items.Add is called, I want to be able to then call UpdateInnerList.

How can I do this?

+2  A: 

How about creating a List subclass and overriding the Add method?

void Main()
{
    var x=new MySpecialList<string>();
    x.Add("hello");
}

class MySpecialList<T>:List<T>
{
    public new void Add(T item)
    {
        //special action here
        Console.WriteLine("added "+item);
        base.Add(item);
    }
}
spender
And if it's stuffed into the base `List<T>` as a variable, this `.Add` will never be called.
Marc
"stuffed into the base..."? I don't understand what you mean.
spender
`List<int> items = new MySpecialList<int>(); items.Add(5);` There is no console output written. It's the bane of using `new` to shadow the base class's method instead of, for example, implementing `IList<T>` instead of what you're suggesting.
Marc
+5  A: 

Can you use the ObservableCollection?

http://msdn.microsoft.com/en-us/library/ms668604.aspx

Wil P
My only caveat about using `ObservableCollection` is that if you need to action the items that are changing, the `.Clear()` method raises the changed event but has no items in the arguments, thus, you do not know what was removed. This is obviously only relevant if you care.
Marc
Good to know. Thanks for commenting.
Wil P
.net 3.5?......
spender
Version Info from the link: Supported in: 4, 3.5, 3.0
Austin Salonen
@Mark, in the case of Clear() I would suspect that a Reset would be the action in the CollectionChanged event. In other cases like Add, Remove I think that there are members on the NotifyCollectionChangedEventArgs that can be used? http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedeventargs.action.aspx
Wil P
Doh. Must learn to read better. ;)
spender
Yes, ObservableCollection is only available 3.5 or higher, but the question is tagged for .Net 3.5.
sixlettervariables
@Wil P, I wish. When you call `.Clear()`, the event is raised (as you say of type Reset) and both `NewItems` and `OldItems` are null. I believe the `NotifyCollectionChangedEventArgs` actually throw if you attempt to circumvent that behavior.
Marc
@Wil P, just reread your comment, yes, the items affected are present for all events on the event arguments _except_ the Reset. This is important to those that wish to action those items there were cleared away.
Marc
Could you provide a code sample? I'm having difficulty getting this to work. Are you sure this will work for WinForms? My research shows this is part of the WPF
Malfist
Nevermind, I just had to add the WindowsBase reference
Malfist
+2  A: 

Try ObservableCollection

It supports a CollectionChanged event which should be what you need.

Shaun Bowe