Pete said:
I suppose I could restate the problem for greater clarity.
Assume I have a form with two buttons, exactly one of which should be
enabled at any instant. The traditional way would be to have the form
consume the Clicked event for both buttons and to have the event handler
for
each button set the Enabled property of the other button to False. I'm
sure,
also, that one could set things up so that the two buttons could mutually
consume each others Clicked events, taking the form out of the mix
altogether.
But both of those approaches get a bit tedious when one introduces 81
buttons and each button has a different set of event trading partners.
Surely it only gets tedious when you need to wire up the events
manually. There's no need for that. For instance, you could have code
like this:
using System;
public class Square
{
const int GridSize = 9;
public event EventHandler Changed;
public static void Main()
{
// Create all the squares
Square[,] grid = new Square[GridSize,GridSize];
for (int i=0; i < GridSize; i++)
{
for (int j=0; j < GridSize; j++)
{
grid[i,j] = new Square();
}
}
// Wire up all the events
for (int i=0; i < GridSize; i++)
{
for (int j=0; j < GridSize; j++)
{
// Other squares in the same row and column
// should subscribe
for (int k=0; k < GridSize; k++)
{
if (k != i)
{
grid[i,j].Changed += new EventHandler
(grid[k,j].ChangeHandler);
}
if (k != j)
{
grid[i,j].Changed += new EventHandler
(grid[i,k].ChangeHandler);
}
}
}
}
}
public void ChangeHandler(object sender, EventArgs e)
{
// Do stuff here
}
}
It would be way cool if it were possible for, say, a single event handler
to
trap the Clicked events for all buttons and, then, re-route those events
(as
events, unchanged) by simply iterating over some data structure that
captures the inter-relationships between buttons.
It would have to know which location had changed though. Either the
square has to know, and tell the event handler that it was that square
(which it would normally do with the "sender" argument), or the event
handler would need to look it up to find the right square.
It would be something like having a generic event (i.e., "some button,
somewhere has been clicked") but, then, only the buttons that need to
know -
based on some higher-level(perhaps dynamically changing) criteria - would
be
notified of that event.
As I say though, you still need the knowledge of what's been clicked
*somewhere*.