Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an Observable Hashset in C#?

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?

like image 359
Michael Avatar asked Feb 09 '09 02:02

Michael


1 Answers

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);
    }
}
like image 181
Matt Hamilton Avatar answered Oct 20 '22 00:10

Matt Hamilton