tags:

views:

82

answers:

2

I am now refactoring a code written by someone else and I have found a construct that I have mixed feelings about. There is a ListView-like control and each of its items can raise 'DialogOpened' event. However, it may be cumbersome to register external event handlers to each of the items (and the items may be added or removed dynamically!). For that reason there is a single event in the ListView-like control and it is named 'ItemDialogOpened'. It sounds all reasonable for me, but there are two issues:

  1. There is a method 'OnItemDialogOpened' in the ListView-like control raising the single event, but this method is not called directly. Instead, it is registered as an event handler to 'DialogOpened' event of each item. It that ok? I am asking, because I was unable to find anything similar to it in the MSDN.
  2. If such event redirection is ok, then who should be the sender of that final, single event? Now, in the code I am working with it is the original sender - the item. However, I think (but I am not sure about it), that now the sender should be changed to the ListView-like control. Am I right?
+2  A: 

For 2 - it is a little bit open to interpretation. Generally you would expect the sender to be the thing you subscribed to; any other information should be conveyed via the args - but there are exceptions, where (for example) the individual item comes through as the sender.

The important thing is to document it clearly.

Marc Gravell
+1  A: 

For 1: This approach does not fully fit into standard flow pattern. From my point of view you must hide your own implementation logic in private method (this method will be end-point for each item DialogOpened event), and then this method will call protected virtual method OnItemDialogOpened. In this case listview can be inherited, communication logic will be transparent and more ms-like, and subscriber will work without casting (because casting is hidden in your private method). Something like that:

private void DialogOpenedHandler(object sender, EventArgs e)
{
    OnItemDialogOpened(new ItemEventArgs((YourItemClass)sender);
}

protected virtual OnItemDialogOpened(ItemEventArgs e)
{
    // call event here 
}
arbiter