In C# (.NET 4.5) I would like to subscribe to an event while I'm creating an object.
The following, of course, would work:
CheckBox c = new CheckBox();
c.Name = "TheCheckBox";
c.Checked += c_Checked;
But want to find out if it's possible to do something along the lines of:
CheckBox c = new CheckBox() {
Name = "TheCheckBox",
Checked += c_Checked
}
Post-discussion edit: This is in order to accomplish is something like:
MyUniformGrid.Add(new CheckBox() {
Name = "TheCheckBox",
Checked += CheckHandler
});
You just subscribe to the event on the other class the same way you would to an event in your form. The three important things to remember: You need to make sure your method (event handler) has the appropriate declaration to match up with the delegate type of the event on the other class.
To subscribe to events, call the EvtSubscribe function. You can subscribe to events from one or more Admin or Operational channels. The channel can exist on the local computer or a remote computer. To specify the events that you want to subscribe to, you can use an XPath query or a structure XML query.
Subscribing to Events. To subscribe to events, call the EvtSubscribe function. You can subscribe to events from one or more Admin or Operational channels. The channel can exist on the local computer or a remote computer.
To subscribe to events by using an anonymous method. If you will not have to unsubscribe to an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.
No, unfortunately event subscription isn't supported within object initializers. It would make it really simple to create GUIs in some cases, but no...
The half-way house is:
Checkbox c = new CheckBox { Name = "TheCheckBox" };
c.Checked += c_Checked;
(Ideally renaming c_Checked
to a name which is actually meaningful - I hate the VS-generated names here...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With