I have instances of a class MyClass, a and b. MyClass has a field Text. I would like to assign an event MyEvent(MyClass target) to b.Selected, such that when fired, this event modifies a.Text. I have some code that looks like this:
void MainMethod()
{
var a = new MyClass();
a.Text = "Foo";
var b = new MyClass();
b.Selected += MyEvent(a); // Make the event fire when b is "selected"
}
void MyEvent(MyClass target) {
target.Text = "Bar";
}
To clarify, my intention is that a‘s Text will be “Foo”, but if b‘s Selected event fires, it a‘s Text will become “Bar”.
I tried to implement something similar to the above, but it did not work. (VS2010 claimed that MyEvent(a) is an event with a null argument, even though I don’t see why a is null.)
I don’t understand events very well (I’m trying to learn them) so sorry if this is obvious.
DETAILS:
In practice, I am using a LabelSelectable not MyClass. LabelSelectable extends Control, which is a class for displaying various things such as pictures, buttons and labels on a screen (this is XNA if relevant). Basically in this case, a bunch of these selectable labels can be cycled through with arrows, and if you press Enter when on a given label, its Selected event fires.
I was actually following this tutorial, and you can find the details of the implementation there. (I don’t mean to be unhelpful but I’m not sure exactly what parts are relevant and what are not, and if I put everything here, it would be a lot of code.)
As far as I can see, “MyClass” looks something like this:
MyClass
{
public event EventHandler Selected;
public string Text
{
get { return text; }
set { text = value; }
}
void OnSelected(EventArgs e)
{
if (Selected != null)
{
Selected(this, e);
}
}
}
I can get the equivalent of the below code to work, by the way:
void MainMethod()
{
var a = new MyClass();
a.Text = "Foo";
var b = new MyClass();
b.Selected += MyEvent; // Make the event fire when b is "selected"
}
void MyEvent(object sender, EventArgs e) {
Console.WriteLine("Event fired!");
}
It would output stuff to the console when b is Selected.
You shouldn’t be placing parameters in your event handler declaration.
b.Selected += MyEvent(a); // Make the event fire when b is "selected"should just be
b.Selected += MyEvent; // Make the event fire when b is "selected"Either MyClass should be responsible for passing the value of target to the invocation of Selected or you must rely on the MyEvent method itself to determine which object to modify.
It may be adventageous to follow a standard eventing pattern where the source of the event is passed in as a parameter to the event handler: