$BlogRSDURL$>
This blog will describe some of the learning experiences that I have with .NET, some personal projects that I'm working on, and whatever other topics tickle my fancy.
My Blog LinksSite Links
Currently ReadingBlogroll
Archives
Tools |
Friday, March 26, 2004ArrayList with Events (Part 3)
Now, let's put it all together and see how we handle events from EventedArrayList and EventedListItems in a sample application.
The sample test application that I created contains a ListView which is updated only in response to events from EventedArrayList and EventedListItem classes. It also has several buttons that directly operate on the ArrayList (things like add an item, remove an item, clear the whole list, and update item data). Let's have a look at the EventedListItem-derived class for my test application. This contains the data and functionality specific for my application -- granted that it's rather simple in this scenario.
Again, pretty simple. It just provides 2 properties that I use to display in the ListView. Each property's setter calls FireAllChangedEvents to fire the appropriate event through any EventedArrayList that this item is associated with. This could be made more complex: to only fire one event for all the changes, or even one event for changes across multiple items (if you had some sort of transacted system). But, for our purposes, just the basic implementation. Now, let's look at how we register for the events that we're interested in:
It works the same way as any other event registration that you're familiar with in .NET: just create an instance of your handler with the method in your class, and add it to the event handler list. Here's the code that handles these events for the Form:
Pretty straight-forward stuff: just go through the list of items in the EventArgs, and depending on which event you're handling, either add, remove, or update the corresponding item in the ListView. You'll notice a MappedListViewItem class being used. I just created this class to map a ListView item with its backing data object. It derives from ListViewItem and just adds a MappedDataObject property. This allows you to cache away which object is associated with that particular ListView item, which will usually be needed in event handling for the ListView. I won't go over that code here, but you can look at it in the sample download if you're interested in what it does. So, that's it -- an ArrayList that fires events, items in that list which also notify observers when they've changed, and sample code of user interface that responds to those events and updates appropriately. You can download the full sample code from GotDotNet or look at it online and report bugs at the workspace.
Comments:
Post a Comment
|