views:

1141

answers:

2

Currently I am using an ObservableCollection within a WPF application, the application is an implementation of Conway's Game of life and works well for about 500 cells but after that it begins to slow down significantly. I originally wrote the application using a HashSet but couldn't find any way to bind the cells to a canvas. Is there a way to get my HashSet to notify its binding object of changes? My Cell class is a simple integer X,Y pair, if the pair exists the cell is alive otherwise dead. The Cell implements INotifyPropertyChanged and overrides GetHashCode and Equals. I couldn't get the cell to display any changes, just the cells present immediately after loading. Is there any way to Bind a Hashset to items on a Canvas?

Thanks

Michael

+7  A: 

You have to implement INotifyCollectionChanged too, and then it should all work OK. There's another relevant SO answer which uses freezables to ensure that changes in underlying entities are also handled.

MrTelly
Hmm, I will take a look at that, INotifyCollectionChanged might just be my missing link, thanks!
Michael
+7  A: 

I don't know if this will help, but here's a really simple implementation of an "observable set" that I made for a personal project. It essentially guards against inserting (or overwriting with) an item that is already in the collection.

If you wanted to you could simply return out of the methods rather than throwing an exception.

public class SetCollection<T> : ObservableCollection<T> 
{
    protected override void InsertItem(int index, T item)
    {
        if (Contains(item)) throw new ItemExistsException(item);

        base.InsertItem(index, item);
    }

    protected override void SetItem(int index, T item)
    {
        int i = IndexOf(item);
        if (i >= 0 && i != index) throw new ItemExistsException(item);

        base.SetItem(index, item);
    }
}
Matt Hamilton
This is very close to what I already have, I use an observablecollection and simply guarantee that all items are unique. In my code rather than through inheritance but hey i'm a wimp ;)
Michael
Yeah I'd say that this is easier than reimplementing HashSet so that it implements INotifyCollectionChanged. All the hard work is already being done by ObservableCollection<T> for you.
Matt Hamilton
going off of reflector it appears that you would want to only expose the default constructor or implement the others yourself, as the base calls a private `CopyFrom` Method instead of `InsertItem`
Maslow